设计模式—单例模式(java)
一:懒汉式
1: 线程安全的双重锁检查机制
public class Singleton{
private Singleton() {} // 私有构造函数,保证不被外界实例化(不考虑反射)
private static Singlecton single = null;
public static Singlecton getInstance()
{ if (singleton == null)
{
synchronized (Singleton.class)
{ if (singleton == null)
singleton = new Singleton();
}
}
return singleton
}
}
2:静态内部类:线程安全,不用加锁
public class Singleton {
private static class LazyHolder{
private static final Singleton INSTANCE = new Singleton ();
}
private Singlecton() {}
public static final Singlecton getInstance()
{
return LazyHolder.INSTSNCE;
}
}
这里总结一下静态内部类:
A:静态内部类,只能访问外部类的静态成员。
B:静态内部类可以实例化
C:静态内部类随着类加载而产生(在类加载的时候,静态成员就生成了)
二:饿汉式:
public class Singleton{
private Singlecton() {}
pribate static final Singlecton single = new Singleton();
public static Singlecton getInstance()
{
return single;
}
}