单例模式的8种写法

第一种: 饿汉式(静态常量) 【可用】

    private class Singleton{
        //私有静态常量对象
        private final static Singleton INSTANCE = new Singleton();
        private Single() {}
        private static Singleton getInstance(){
            return INSTANCE; 
        }
    }

第二种: 饿汉式(静态代码块)【静态代码块】

    private class Singleton{
        private Singleton instance;
        static{
            instance = new Singleton();
        }
        private singleton(){}

        private static Singleton getInstance(){
            return intance;
        }
    }

第三种: 懒汉式 (线程不安全) 【不可用】

public class Singleton{

    private static Singleton instance = null;

    private Singleton() {}

    private static Singleton getInstance(){
        if(null == instance){
            instance = new Singleton();
        }
        return instace;
    }

第四种:懒汉式 (线程安全,同步方法) 【不推荐用】

private class Singleton{
    private static Singleton instance = null;
    private Singleton (){}
    private static synchronized Singleton getInstance(){
        if(null == instance){
            instance = new Singleton();
        }
        return instance;
    }
}

可以解决线程不安全问题,缺点是效率太低。每一次执行getInstance()时都需要同步。

第五种: 懒汉式 (线程安全,同步代码块)【不可用】

private class Singleton{

    private static Singleton instance = null;
    private Singleton () {}

    private static Singleton getInstance() {
        if(null == instance){
            systchronized(Singleton.class) {
                instance = new Singleton();
            }
        }
        return instance;
    }
}

此处的同步代码块并不能起到线程同步的作用,当一个线程进入到if(Singgleton == null)语句块后,
还没来得及继续执行,另一个线程也通过了这个判断语句,这是会产生多个实例。

第六种 : 双重检查【推荐用】

private class Singleton{
    private static Singleton instatnce = null;
    private Singleton () {}
    private static Singleton getInstance() {
        if(null == instance ){
            sychronized(Singleton.class) {
                if(null == instance){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

第七种: 静态内部类 【推荐用】

    private class Singleton{

        private Singleton() {}

        private static class SingletonInstance(){
            private final static Singleton INSTANCE = new Singleton();
        }

        private static Singleton getInstance(){
            return SingletonInstance.INSTANCE ;
        }

    }

第八种: 枚举【推荐用】


public enum Singleton{
    INSTANCE;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值