单例模式
2018-08-23 本文已影响0人
ybyao
概念
一种创建型模式,确保系统中一个类只产生一个实例
好处
1 频繁使用的对象,可以省略创建对象所花的时间
2 New操作次数减少,因为系统内存的使用频率也会降低(减轻GC压力和GC停顿时间)
例子
public class Singleton{
private Singleton(){
System.out.println("create singleton");
if (SingleHolder.singleton != null){
throw new IllegalStateException();
}
}
private static class SingleHolder{
private static Singleton singleton = new Singleton();
}
public static Singleton getInstance(){
return SingleHolder.singleton;
}
}