创建型:单例模式

单例模式(Singleton Pattern):保证一个类只有一个实例,并提供一个访问它的全局访问点。

单例模式的要点:

  • 类只能有一个实例。
  • 必须自行创建这个实例。
  • 必须自行向整个系统提供这个实例。

实现单例模式的要素:

  • 私有的构造器
  • 一个静态方法
  • 一个静态变量

  1. 优点
    • 单例模式提供了对唯一实例的受控访问。
    • 节约系统资源。
  2. 缺点
    • 单例没有抽象层,扩展很难。
    • 单例类职责过重,违背了“单一职责原则”。
    • Java存在垃圾回收,如果单例对象被自动销毁并回收,下次利用时又将重新实例化,这将导致共享单例对象的状态丢失。
  3. 适用场景
    • 系统只需要一个实例对象,或者需要考虑资源消耗只允许创建一个对象。
    • 单个实例只允许一个公共访问点。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package creator.singleton;
public class Singleton {
private static Singleton instance;
/**
* 私有构造方法, 防止被实例化
*/
private Singleton() {
}
/**
* 实现懒加载, 但无法应对多线程环境(可能会返回多个不同的实例)
* @return
*/
public static Singleton getInstance1(){
if (instance == null){
instance = new Singleton();
}
return instance;
}
/**
* 加上同步
* 问题:只有第一次执行该方法的时候才真正需要同步,一旦设置了instance变量, 就不再需要同步这个方法
* 同步方法可能造成程序执行效率的下降
* @return
*/
public static synchronized Singleton getInstance2(){
if (instance == null){
instance = new Singleton();
}
return instance;
}
/**
* 急切创建, 不用延迟实例化
* private static Singleton instance = new Singleton();
*
* @return
*/
public static Singleton getInstance3(){
return instance;
}
/**
* 双重检查加锁
* private volatile static Singleton instance;
* @return
*/
public static Singleton getInstance4(){
if (instance == null){
synchronized (Singleton.class){
if (instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}