普通写法(饿汉式)
public class Single {
private static final Single INSTANCE = new Single();
public static Single getINSTANCE() {
return INSTANCE;
}
}
// 线程安全 因为类加载的时候就直接加载了 所以是线程安全的
懒汉式
public class Single {
private static Single INSTANCE = null;
public static Single getINSTANCE() {
if (INSTANCE == null){
INSTANCE = new Single();
}
return INSTANCE;
}
//最基础的写法 非线程安全
}
升级一点的写法
public class Single {
private static Single INSTANCE = null;
public static synchronized Single getINSTANCE() {
if (INSTANCE == null){
INSTANCE = new Single();
}
return INSTANCE;
}
//线程安全 ,但是效率降低
}
再升级一点的写法
public class Single {
private static volatile Single INSTANCE = null;
public static Single getINSTANCE() {
if (INSTANCE == null){
synchronized (Single.class){
if (INSTANCE == null){
INSTANCE = new Single();
}
}
}
return INSTANCE;
}
//线程安全 ,但是效率提高了 (volatile 关键字是 防止重排序,但需要检验两次)
}
内部类写法
public class Single {
public static Single getINSTANCE() {
return Holder.INSTANCE;
}
public static class Holder{
private static final Single INSTANCE = new Single();
}
// 静态内部类写法, 类加载的时候才加载,而内部类是与外部类同级的,只有用到内部类的时候才加载内部类
}
枚举类写法
public enum Single {
INSTANCE
}
// 天生单例 effectiviejava 推荐,
网友评论