单例模式概念
- 一个类只能有一个实例
- 由自己创建的唯一实例
- 给其他对象提供这一实例
应用场景
- 建立数据库连接
- 计数器
- 唯一序列号
实现案例
- 类加载时初始化,多线程安全
1 2 3 4 5 6 7
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
public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton (){} public static final Singleton getInstance() { return SingletonHolder.INSTANCE; } }
- 防止反序列化重新创建的枚举类型,多线程安全
1 2 3 4 5
public enum Singleton { INSTANCE; public void method() { } }
- 初始化懒加载,双锁机制,多线程情况下能保持高性能
1 2 3 4 5 6 7 8 9 10 11 12 13 14
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; } }