单件模式:确保一个类只有一个实例,并提供一个全局的访问点。
使用场景:windows任务管理器,回收站,线程池的设计也是采用单件模式,方便线程池对池中的线程进行控制。
类图:
一个私有静态实例变量,一个private构造方法,一个公有静态方法
示例:
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {
}
public static Singleton getUniqueInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
在多线程情况下,三种解决方式:
- 加锁
public static synchronized Singleton getUniqueInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
- 提前创建好实例
private static Singleton uniqueInstance = new Singleton();
- 双重检查加锁
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {
}
public static Singleton getUniqueInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}