手写设计模式

单例模式

饿汉式

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 禁止指令重排,先初始化再引用指向。
相关推荐
啦啦啦啦啦zzzz16 小时前
设计模式:桥接模式和组合模式
c++·设计模式·组合模式·桥接模式
莫得感情 o19 小时前
设计模式 03 · 工厂方法模式
设计模式·工厂方法模式
饼干哥哥1 天前
字节Seedance2.5终于上线,这次在收割谁?
人工智能·设计模式·前端框架
董员外2 天前
RAG 系统进化论(六):GraphRAG(基于知识图谱的 RAG),从相似文本走向实体关系
人工智能·后端·设计模式
鬼鬼鬼2 天前
从 Prompt 到 Harness:企业级 Agent 工程的完整演进之路
设计模式·架构·ai编程
啦啦啦啦啦zzzz2 天前
设计模式:原型模式
c++·设计模式·原型模式
董员外2 天前
RAG 系统进化论(五):Corrective RAG 与 Self-RAG,让系统发现并纠正错误
人工智能·后端·设计模式
workflower2 天前
高质量数据集的类型
人工智能·机器学习·设计模式·自然语言处理·机器人
啦啦啦啦啦zzzz2 天前
工具:动态类工厂和用配置文件存储属性
c++·设计模式·工具·动态工厂
Nontee3 天前
设计模式:模板方法与策略,从“每个字都认识“到能说清它们在干嘛
java·数据库·设计模式