Java单例模式的思考

单例模式的特征
  • 私有的构造函数
  • 提供静态变量
  • 提供静态的获取实例方法
单例模式六种写法
  • 饿汉式单例模式
public class Singleton {
    private static Singleton sInstance = new Singleton();

    private Singleton() {
    }

    public static Singleton getInstance() {
        return sInstance;
    }
}
  • 懒汉式单例模式
public class Singleton {
    private static Singleton sInstance = null;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (sInstance == null) {
            sInstance = new Singleton();
        }
        return sInstance;
    }
}
  • 懒汉式单例模式(线程安全)
public class Singleton {
    private static Singleton sInstance = null;

    private Singleton() {
    }

    public static synchronized Singleton getInstance() {
        if (sInstance == null) {
            sInstance = new Singleton();
        }
        return sInstance;
    }
}
  • 双重检查锁实现单例模式
public class Singleton {
    private static volatile Singleton sInstance = null;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (sInstance == null) {
            synchronized (Singleton.class) {
                if (sInstance == null) {
                    sInstance = new Singleton();
                }
            }
        }
        return sInstance;
    }
}
  • 静态内部类实现单例模式
public class Singleton {
    
    private Singleton() {
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
}
  • 枚举实现单例模式
public enum Singleton {
    INSTANCE;

    public static Singleton getInstance() {
        return INSTANCE;
    }
}
  • CAS操作实现单例
// CAS操作实现单例
public class Singleton {
    private static final AtomicReference<Singleton> INSTANCE = new AtomicReference<>();

    public Singleton getInstance() {
        for (; ; ) {
            Singleton singleton = INSTANCE.get();
            if (singleton != null) {
                return singleton;
            }
            singleton = new Singleton();
            if (INSTANCE.compareAndSet(null, singleton)) {
                return singleton;
            }
        }
    }
}
单例模式注意点
  • 反射可能会破坏单例模式,通过反射可以强制调用构造函数,生成对象实例,这里构造函数内部可以加入判断,如果对象实例已存在,则抛出异常,禁止再次调用。
  • 反序列化可能会破坏单例,反序列还的过程中,会重新生成对象,这里可以在单例类中定义一个readResolve()方法,内部返回已创建的实例,使其在反序列化的过程中调用该方法,仍然返回之前的实例。
  • 克隆可能会破坏单例模式,通过重写clone方法,返回已创建的实例
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值