单例模式

在一个系统中,要求一个类有且仅有一个对象,如果出现多个对象就会出现“混乱”。

  • 要求生成唯一序号的场景
  • 整个项目中需要一个共享数据,如计数器
  • 创建对象要消耗过多资源(IO访问或者数据库资源等)
  • 定义大量的静态常量和静态方法的工具类

定义

确保一个类只有一个实例,而且自行实例化并且向整个系统提供这个实例。

优点

单例模式在内存中只有一个实例,减少了内存开支。
当一个对象需要频繁地创建、销毁时,而且创建或者销毁时的性能无法优化时,单例模式的优势非常明显。

缺点

没有接口,无法扩展,没有接口也不能使用Mock方式虚拟对象。
在并行开发环境中,单例模式没有完成无法进行测试。
与单一职责原则冲突,单例模式把业务逻辑和单例混合在一个类中。

注意事项

高并发情况下,单例模式的线程同步问题。

提前加载

1
2
3
4
5
6
7
8
9
10
public class Singleton{

private static Singleton instance = new Singleton();

private Singleton(){}

public static Singleton getInstance(){
return instance;
}
}

延后加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Singleton{

private volatile static Singleton instance = null;

private Singleton(){}

public static Singleton getInstance(){
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}

}

枚举

1
2
3
public enum Singleton{
instance;
}