设计模式之单例模式

单例模式

确保任何情况下都绝对只有一个补全。像这样的被称为单例模式。

创建单例模式的五种方式

1. 饿汉式

public class Hungry {
    private static Instance instance = new Instance();

    private Hungry() {}

    public static Instance getInstance() {
        return instance;
    }
}
  • 线程安全
  • 实例占用资源多或初始化耗时长,提前初始化实例是一种浪费资源的行为。最好的方法应该是用到的时候再去初始化。
  • 如果初始化耗时长,那我们最好不要等到正在要用到它的时候,才去执行这个耗时长的初始化过程,这会影响到系统的性能。

2. 懒汉式(非线程安全)

public class Lazy {
    private static Instance instance;
    private Lazy() {}
    public static Instance getInstance() {
        if (instance == null) {
            instance = new Instance();
        }
        return instance;
    }
}

3. DCL(Double Check Lock)

public class DCL {
    private static Instance instance;
    private DCL() {}

    public static Instance getInstance() {
        if (instance == null) {
            synchronized (DCL.class) {
                if (instance == null) {
                    instance = new Instance();
                }
            }
        }
        return instance;
    }
}

注意: 这种方式还是存在线程安全。因为指令重排序,可能会导致Instance对象被new出来,并且赋值给instatnce之后,还没有来得及初始化(执行构造函数中的代码逻辑),就被另一个线程使用了。

TimeThread AThread B
T1检查到instance为空
T2获取锁
T3再次检查到instance为空
T4instance分配内存空间
T5instance指向内存空间
T6检查到instance不为空
T7访问instance(此时对象还未完成初始化)
T8初始化instance

4. DCL + volatile

public class DCLPlus {
    private volatile static Instance instance;
    private DCLPlus() {}

    public static Instance getInstance() {
        if (instance == null) {
            synchronized (DCLPlus.class) {
                if (instance == null) {
                    instance = new Instance();
                }
            }
        }
        return instance;
    }
}

5. 枚举

public enum  EnumSingleton {
    INSTANCE;
    public Instance getInstance() {
        return new Instance();
    }
}

6.静态内部类

public class StaticInner {
    private StaticInner() {}
    
    private static class SingleonHolder {
        private static final Instance instance = new Instance();
    }
    
    public static Instance getInstance() {
        return SingleonHolder.instance;
    }
}

SingleonHolder是一个静态内部类,当外部类StaticInner被加载的时候,并不会创建该实例对象。只有当调用getInstance()方法时,SingleonHolder才会加载,这个时候才会创建instance。insance 的唯一性、创建过程的线程安全性,都由JVM 来保证。所以,这种实现方法既保证了线程安全,又能做到延迟加载。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值