单例模式要点
- 私有的构造方法
- 指向实例的私有静态引用
- 获取实例对象的公有静态方法
饿汉模式(非线程安全)
public class SingleTon {
private SingleTon(){}//私有化构造函数
private static final SingleTon singleTon=new SingleTon();
public static SingleTon getInstance(){
return singleTon;
}
}
懒汉模式(非线程安全)
public class SingleTon {
private SingleTon() {}//私有化构造函数
private static SingleTon singleTon;
public static SingleTon getInstance() {
if (singleTon == null)
singleTon = new SingleTon();
return singleTon;
}
}
双重线程锁检查单例(线程安全)
public class SingleTon {
private SingleTon() {}//私有化构造函数
private static volatile SingleTon singleTon;
public static SingleTon getInstance() {
if (singleTon == null){
synchronized (SingleTon.class){
SingleTon st=singleTon;
if (st == null) {
st=new SingleTon();
singleTon=st;
}
}
}
return singleTon;
}
}
枚举单例
public enum SingleTon{
Instance;
}