意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
实现(单线程):
public class Singleton {
private static Singleton uniqueInstance; // 自己管理唯一实例变量
private Singleton() {} // 构造器私有
public static Singleton getInstance() {
if (uniqueInstance == null)
uniqueInstance = new Singleton(); // 需要用时才实例化
return uniqueInstance;
}
}
实现(多线程):
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {}
public static synchronized Singleton getInstance() { // 同步方法
if (uniqueInstance == null)
uniqueInstance = new Singleton();
return uniqueInstance;
}
}
实现(多线程改良 1):
public class Singleton {
private static final Singleton uniqueInstance = new Singleton(); // 静态初始化时便创建
private Singleton();
public static Singleton getInstance() {
return uniqueInstance;
}
}
实现(多线程改良 2):
public class Singleton {
private static volatile Singleton uniqueInstance; // 声明为volatile域,保证其可见性
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) { // 同步块
uniqueInstance = new Singleton();
}
}
return uniqueInstance;
}
}