单例模式
定义:
建造模式的一种,保证系统中一个类仅有一个实例,并提供一个全局访问点.
目的:
为了解决系统中保证某种对象的唯一性,以便对全局提供唯一或者状态统一的服务。比如全局计时器,ID生成器,窗口管理器等等。
关键点:
私有的构造方法
公开的静态实例返回方法
类图:
代码实现:
单例设计模式根据不同的需求可实现为懒汉模式(需要时再创建对象),饿汉模式(初始化时及创建对象),双重锁模式等等,以下仅实现双重锁模式 -
public class Singleton{
private static volatile Singleton singleton = null;
private Singleton(){}
public static Singleton getInstance(){
if(singleton == null){
synchronized(Singleton.class){
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}