设计模式 - 单例设计模式

单例设计模式

通过单例设计模式可以保证系统中,应用该模式的类只有一个对象实例

使用场景

  • 业务系统全局只需要一个对象实例,比如发号器、redis 连接对象等
  • Spring IOC 容器中Bean 默认就是单例

分类

  • 懒汉式:就是懒加载,延迟创建对象
  • 饿汉式:与懒汉相反,提前创建对象

实现步骤

  • 私有化构造对象
  • 提供获取实例的构造方法

饿汉式

public class HungrySingleton {
    private static HungrySingleton singleton = new HungrySingleton();

    private HungrySingleton() {
    }

    public static HungrySingleton getInstance() {
        return singleton;
    }
}

懒汉式

线程安全

public class LazySingleton {

    private static LazySingleton singleton = null;

    /**
     * 第一步: 私有构造方法
     */
    private LazySingleton() {}

    /**
     * 提供获取实例的方法 - 线程不安全
     * @return
     */
    public static LazySingleton getInstance() {
        // 可能多个线程同时创建
        if (null == singleton) {
            singleton = new LazySingleton();
        }
        return singleton;
    }
}

线程不安全

public class DCLLazySingleton {
    /**
     * 使用volatile
     * 保证 singleton = new DCLLazySingleton(); 原子性
     * 1. 在内存开辟空间给对象
     * 2. 在空间内创建对象
     * 3. 将对象赋值给引用变量
     *
     */
    private static volatile DCLLazySingleton singleton = null;

    private DCLLazySingleton() {}

    public static DCLLazySingleton getInstance() {
        if (null == singleton) {
            // 可能有多个线程进入
            synchronized (DCLLazySingleton.class) {
                // 所以再判断
                if (null == singleton) {
                    singleton = new DCLLazySingleton();
                }
            }
        }

        return singleton;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值