早上随便翻到单例的写法,那我也随手写几个吧
public class SingleClassTest {
//定义一个private的构造方法,就是防止外部通过new SingleClassTest去实例化
private SingleClassTest(){}
//普通饿汉写法
private static final SingleClassTest INSTANCE = new SingleClassTest();
private static SingleClassTest getInstance(){
return INSTANCE;
}
//普通懒汉写法
private static SingleClassTest INSTANCE = null;
private static SingleClassTest getInstance(){
if (INSTANCE == null){
INSTANCE = new SingleClassTest();
}
return INSTANCE;
}
//禁止重排序,double-check写法
private static volatile SingleClassTest INSTANCE = null;
private static SingleClassTest getInstance(){
if (INSTANCE == null){
synchronized (SingleClassTest.class){
if (INSTANCE == null){
INSTANCE = new SingleClassTest();
}
}
}
return INSTANCE;
}
//静态内部类写法
private static SingleClassTest getInstance(){
return InnerSingleClass.INSTANCE;
}
private static class InnerSingleClass{
private static final SingleClassTest INSTANCE = new SingleClassTest();
}
}
除了以下几种,需要知道枚举也是属于一种实现方式,并且它可以防止序列化/反序列化、反射
public enum SingleClassTest {
INSTANCE;
public static SingleClassTest getInstance(){
return INSTANCE;
}
}