/**
* @author BNTang
*/
public class Singleton {
/**
* 没有延迟加载,好长时间不使用,影响性能
*/
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
/**
* @author BNTang
*/
public class SingletonTwo {
private static SingletonTwo instance = null;
private SingletonTwo() {
}
public synchronized static SingletonTwo getInstance() {
if (instance == null) {
instance = new SingletonTwo();
}
return instance;
}
}
/**
* @author BNTang
*/
public class SingletonThree {
private static volatile SingletonThree instance = null;
private SingletonThree() {
}
public static SingletonThree getInstance() {
// Double-Check-Locking, DCL
if (instance == null) {
synchronized (SingletonThree.class) {
if (instance == null) {
instance = new SingletonThree();
}
}
}
return instance;
}
}
创建对象步骤
memory = allocate(); // 1:分配对象的内存空间
ctorInstance(memory); // 2:初始化对象
instance = memory; // 3:设置 instance 指向刚分配的内存地址
memory = allocate(); // 1:分配对象的内存空间
instance = memory; // 3:设置 instance 指向刚分配的内存地址
// 注意,此时对象还没有被初始化!
ctorInstance(memory); // 2:初始化对象
/**
* @author BNTang
*/
public class SingletonFour {
private SingletonFour() {
System.out.println("SingletonFour 初始化了");
}
/**
* 第一次使用到的时候才去执行, 只执行一次
*/
private static class Holder {
private static SingletonFour instance = new SingletonFour();
}
public static SingletonFour getInstance() {
return Holder.instance;
}
}
反序列化问题
// 该方法在反序列化时会被调用
protected Object readResolve() throws ObjectStreamException {
System.out.println("调用了readResolve方法!");
return Holder.instance;
}
/**
* @author BNTang
*/
public enum SingletonFive {
/**
* 单值的枚举就是一个单例
*/
INSTANCE;
private static int a = 0;
public static void add() {
a++;
System.out.println(a);
}
public static SingletonFive getInstance() {
return INSTANCE;
}
}
/**
* @author BNTang
*/
public class SingletonSix {
private SingletonSix() {
}
private enum Holder {
INSTANCE;
private SingletonSix instance = null;
Holder() {
instance = new SingletonSix();
}
private SingletonSix getInstance() {
return instance;
}
}
public static SingletonSix getInstance() {
return Holder.INSTANCE.getInstance();
}
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。