方案一
1 2 3 4 5 6 7 8 9 10 11 12
| public class Singleton { private static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } }
|
缺点:无法应对多线程的场景,即使将getInstance()
加上synchronized
关键字也会带来性能方面的问题。
方案二:饿汉模式
1 2 3 4 5 6 7 8 9
| public class Singleton { private static Singleton uniqueInstance = new Singleton();
private Singleton() {}
public static Singleton getInstance() { return uniqueInstance; } }
|
方案三:双重检查加锁+饿汉模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class Singleton { private volatile static Singleton uniqueInstance; private Singleton() {} public static Singleton getInstance() { if (uniqueInstance == null) { synchronized (Singleton.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } } } return uniqueInstance; } }
|