简述
单例 (Singleton) 模式提供一个可以全局访问的实例,并保证该类仅有一个实例。
设计模式类型:创建型
实现
1.懒汉 多线程不安全
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class Singleton { private static Singleton instance;
private Singleton() { }
public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
|
2.懒汉 多线程安全
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class Singleton { private static Singleton instance;
private Singleton() { }
public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
|
3.双检锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| 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; } }
|
4.饿汉
1 2 3 4 5 6 7 8 9 10
| public class Singleton { private static final Singleton instance = new Singleton();
private Singleton() { }
public static Singleton getInstance() { return instance; } }
|
5.静态内部类
1 2 3 4 5 6 7 8 9 10 11 12
| public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); }
private Singleton() { }
public static Singleton getInstance() { return SingletonHolder.INSTANCE; } }
|
6.枚举
1 2 3
| public enum Singleton { INSTANCE; }
|
选择
不建议使用 1 和 2
不考虑继承问题使用 6 枚举
单例是派生类,确定会使用,建议使用 4 饿汉
单例是派生类,且不确定单例是否会使用,考虑 3 双检锁 或 5 静态内部类