手写设计模式

单例模式

饿汉式

java 复制代码
public class SingleTon {

    private static SingleTon instance = new SingleTon();

    private SingleTon(){};

    public static SingleTon getInstance(){
        return instance;
    }
}

要点:

  1. 静态 private instance
  2. 私有的构造器
  3. 方法返回 instance

懒汉式

java 复制代码
public class SingleTon {

    private volatile static SingleTon instance;

    private SingleTon(){}

    public static SingleTon getInstance(){

        if(instance == null){
            synchronized (SingleTon.class){
                if(instance == null){

                    instance = new SingleTon();
                }
            }
        }
        return instance;
    }
}

要点:

  1. volatile 修饰 instance
  2. 双端锁检验
  3. 构造器私有化

为什么需要 volatile:

主要由于双端锁检验和指令重排共同造成的问题:

  1. 双端锁减少了在锁外等待的线程,提高了效率但是也造成了问题。
  2. new 对象的过程
    1. 分配空间
    2. 初始化对象
    3. 引用指向对象
  3. 其中第 2,3 步可能会重排,造成 instance 判断不为空,但是并未初始化,结果该线程不再等待锁直接返回了 instance,此时 instance 未被初始化,线程不安全。
  4. volatile 禁止指令重排,先初始化再引用指向。
相关推荐
阿狗童鞋9 小时前
设计模式实战指南
设计模式
电子科技圈14 小时前
基于车载SerDes和OpenGMSL协议的SoC设计与验证:行业高频问题解析
设计模式·车载系统·软件构建·设计规范
ClinicTech16 小时前
高速冷冻离心机的温控系统与安全保护逻辑解析
设计模式·架构·健康医疗·设计语言
GISMagic21 小时前
3.《设计模式》:软件设计与解耦能力提炼
设计模式·ai coding
染指111021 小时前
131.Agent-Agent设计模式-MAS多智能体系统(Multi-Agent-System)
人工智能·设计模式·langchain·agent·agents
ShyanZh1 天前
【Python3基础】13-Python 常用设计模式
开发语言·python·设计模式
YYYing.2 天前
【设计模式系列 (五) 】原型模式
开发语言·后端·设计模式·原型模式·c/c++
长按助力退休2 天前
设计模式实战,这 5 个最常用
设计模式
Carl_奕然3 天前
【智能体】Agent的四种设计模式之:Multi-Agent Collaboration
设计模式
Lost of 程序猿3 天前
建造者模式实战:告别“十参数构造函数“的数据导出任务
后端·设计模式·c#·asp.net