单例模式
一个单一的类,负责创建自己的对象,同时确保只有单个对象被创建。
单例模式三种最典型的懒加载单例写法:
双重检查锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class Singleton {
private static volatile Singleton INSTANCE = null;
public static Singleton getInstance() { if (INSTANCE == null) { synchronized (Singleton1.class) { if (INSTANCE == null) { INSTANCE = new Singleton(); } } }
return INSTANCE; } }
|
静态内部类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class Singleton {
private static class SingletonHolder { private final static Singleton INSTANCE = new Singleton(); }
public static Singleton getInstance() { return SingletonHolder.INSTANCE; }
private Singleton() {} }
|
枚举
1 2 3 4 5 6 7 8
| public enum Singleton { INSTANCE;
public static Singleton getInstance() { return Singleton.INSTANCE; } }
|