确保一个类只有一个实例,并提供一个访问它的全局访问点。
类图

实现
懒汉式-线程不安全
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class Singleton {
private static Singleton uniqueInstance;
private Singleton() { }
public static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; }
}
|
饿汉式-线程安全
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class Singleton2 {
private static Singleton2 uniqueInstance = new Singleton2();
private Singleton2() { }
public static Singleton2 getInstance() { return uniqueInstance; }
}
|
双重校验锁-线程安全
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class Singleton3 {
private volatile static Singleton3 uniqueInstance;
private Singleton3() { }
public static Singleton3 getInstance() { if (uniqueInstance == null) { synchronized (Singleton3.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton3(); } } } return uniqueInstance; }
}
|