设计模式是为了解决一些特定的问题,而采用统一的解决方案,方便进行重复使用的一种操作模式(个人理解)
单列设计模式
使用饿汉式 安全
class Single{
private Single(){};
private static Single single = new Single();
public static Single getSingle(){
return single;
}
}
静态内部类方式更为安全和效率更高.静态内部类不保持外部类的引用,并且只有在内部类加载的时候才会初始化,保证了初始化的延迟性,而且JVM会保证并发时,不会创建多余的对象.推荐使用此方法.
public class Singleton {
private Singleton() {
}
public static Singleton getInstance() {
return SingletonInstance.instance;
}
private static class SingletonInstance {
static Singleton instance = new Singleton();
}
}