大家好,又见面了,我是你们的朋友全栈君。
public class LazyNoSafe {
private static LazyNoSafe instance;
public static LazyNoSafe getInstance() {
if (instance == null) {
instance = new LazyNoSafe();
}
return instance;
}
private LazyNoSafe() {}
}
说明:
public class LazySafe {
private static LazySafe instance;
public synchronized static LazySafe getInstance() {
if (instance == null) {
instance = new LazySafe();
}
return instance;
}
private LazySafe() {}
}
说明:
public class LazyUseInner {
private static class InnerClass {
private static LazyUseInner instance = new LazyUseInner();
}
public static LazyUseInner getInstance() {
return InnerClass.instance;
}
private LazyUseInner() {}
}
说明
public class DoubleLock {
private volatile static DoubleLock instance;
public static DoubleLock getInstance() {
if (instance == null) { //第一次检查
synchronized(DoubleLock.class) {
if (instance == null) {
instance = new DoubleLock();
}
}
}
return instance;
}
private DoubleLock() {}
}
说明:
public class HungrySafe {
private static HungrySafe instance = new HungrySafe();
public static HungrySafe getInstance() {
return instance;
}
private HungrySafe() {}
}
说明:
public enum UseEnum {
INSTANCE;
public void otherMethod() {
// do something...
}
}
说明
对于序列化的反序列化可以实现readResolve()来保证单例。 项目中使用单例前最好先思考以下三点:线程安全、延迟加载、序列化与反序列化安全。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/160045.html原文链接:https://javaforall.cn