应用场景
当我们仅需要一个类仅有一个实例,并提供一个访问它的全局访问点,就可以使用单例模式来减少频繁的创建和销毁
优点
- 减少性能开支
- 避免对资源的多重占用,比如多个对象去读写一个文件
- 优化和共享资源访问
实例
懒汉式
- 延迟初始化(懒加载)
- 线程不安全
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
饿汉式
- 线程安全
- 可能产生垃圾对象
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}
登记式/静态内部类
- 是饿汉式的改进
- 线程安全
- 延迟加载
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
双检锁/双重校验锁(DCL,即 double-checked locking)
- 懒加载
- 线程安全
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
枚举
- 实现单例的最佳模式
- 自动支持序列化机制
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}