单例模式
单例模式
标签: 设计模式 java
1. 饿汉模式
public class Singleton{
private Singleton(){}
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}
优点:
- 线程安全
缺点:
- 非懒加载
序列化时必须声明实例域为transient并提供一个readResolve方法,防止重复反序列化
2. 懒汉模式
public class Singleton {
private Singleton() {}
private static Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
优点:
- 懒加载
缺点:
- 非线程安全
3. 懒汉模式(synchronized)
public class Singleton {
private Singleton() {}
private static Singleton instance;
public synchronized static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
优点:
- 使用synchronized修饰getInstance()方法来确保线程安全性
缺点:
- 无论实例是否已创建,getInstance()都需要同步
4. 懒汉模式(DCL)
public class Singleton {
private Singleton() {}
private static Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
优点:
- 线程安全;
- 如果实例已创建,则其他线程在获取实例时可以避免多余的同步操作。
缺点:
- 据说在JDK 1.5后,DCL才能正常达到单例效果,不便于移植(未进行验证)
5. 延迟初始化占位类模式
public class Singleton{
private Singleton(){}
private static class InstanceHolder{
public static Singleton instance = new Singleton();
}
public static Singleton getInstance(){
return InstanceHolder.instance;
}
}
优点:
- 通过类加载机制确保线程安全
- 通过类加载机制实现懒加载;
6. 枚举单例模式(Effective Java推荐)
public enum Evis {
INSTANCE;
public void leaveTheBuilding(){...}
}
从java 1.5起,可以用单元素枚举类型实现单例模式,号称实现单例的最佳方法。
优点:
- 无偿地提供了序列化机制,绝对防止多次序列化;
- 抵御反射攻击(反编译时类的修饰符是abstract);
- 线程安全(类加载机制)。