单件模式:确保一个类只有一个实例,并提供全局访问点。
package headfirst.singleton.dcl;
//
// Danger! This implementation of Singleton not
// guaranteed to work prior to Java 5
//
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;
}
}
package headfirst.singleton.dcl;
public class SingletonClient {
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
}
}