确保一个类只有一个实例的模式成为单例模式。
单例模式的优点:
1.减少内存开支,降低系统性能消耗
2.避免对资源的多重操作,确保只有一个类实例进行动作
缺点:
1. 没有抽象,没有接口,无法被扩展
2. 并行开发,测试不方便,只有能单例模式开发完毕才能对类进行测试
标准类图:
一、标准的单例模式(预先实例化,项目当推荐使用此模式)
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton(){
}
public Singleton getInstance(){
return singleton;
}
}
二、延迟实例化的双锁单例模式(线程安全,但项目中不建议使用,因为可读性不好,也较复杂)
public class SingletonLazy {
private static SingletonLazy singleton = null;
private SingletonLazy(){
}
public SingletonLazy getInstance(){
if(singleton == null){
synchronized (SingletonLazy.class) {
if(singleton == null){
singleton = new SingletonLazy();
}
}
}
return singleton;
}
}
三、单例模式的扩展,只产生限定数量的多例模式
public class SingletonEx {
private static final Integer MAX_INSTANCE_COUNT = 2;
private static List<SingletonEx> instances = new ArrayList<>();
static {
instances.add(new SingletonEx());
instances.add(new SingletonEx());
}
private SingletonEx(){
}
public SingletonEx getInstance(){
Random random = new Random();
return instances.get(random.nextInt(MAX_INSTANCE_COUNT));
}
}