设计模式笔记_五_单件模式
最后更新于
最后更新于
/**
* 经典单件模式
*/
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}/**
* 单件模式
* 使用同步进行多线程处理
*/
public class SingletonWithSync {
private static SingletonWithSync uniqueInstance;
private SingletonWithSync() {}
/**
* 通过增加synchronized关键字到getInstance()方法中
* 迫使每个线程在进入这个方法之前,要先等候别的线程离开该方法
* 也就是说,不会有两个线程可以同时进入这个方法
*/
public static synchronized SingletonWithSync getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new SingletonWithSync();
}
return uniqueInstance;
}
}/**
* 单件模式
* 急切(eagerly) 创建
*/
public class SingletonEagerly {
private static SingletonEagerly uniqueInstance = new SingletonEagerly();
private SingletonEagerly() {}
public static SingletonEagerly getInstance() {
return uniqueInstance;
}
}/**
* 单件模式
* 双重检查加锁(double-checked locking)
*/
public class SingletonDCL {
// volatile关键词确保:当uniqueInstance变量被初始化成Singleton实例时
// 多个线程正确地处理uniqueInstance变量
// volatile不适用1.4及更早版本
private volatile static SingletonDCL uniqueInstance;
private SingletonDCL() {}
public static SingletonDCL getInstance() {
if (uniqueInstance == null) { // 如果实例不存在进入同步区; 只有第一次执行才会彻底执行这里的代码
synchronized (SingletonDCL.class) {
if (uniqueInstance == null) { // 进入区块后,再检查一次,如果仍是null,才创建实例
uniqueInstance = new SingletonDCL();
}
}
}
return uniqueInstance;
}
}