手写设计模式

单例模式

饿汉式

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 禁止指令重排,先初始化再引用指向。
相关推荐
2401_868534782 小时前
网规备考_2.4 路由协议
c++·设计模式
cpp_learner3 小时前
C++ 实现责任链模式(Chain of Responsibility):从一堆 if-else 到可插拔的处理管道
c++·设计模式
码匠许师傅3 小时前
【设计模式精讲】23.备忘录模式(Memento)
c++·设计模式·软件工程·uml·备忘录模式
新知图书20 小时前
第8章 多智能体协同
人工智能·设计模式·智能体
京师20万禁军教头1 天前
39面向对象(高级)-设计模式
java·开发语言·设计模式
新知图书1 天前
3.5 智能体设计模式1:反应式智能体与自动导航案例
人工智能·设计模式·智能体
码匠许师傅1 天前
【设计模式精讲】21.迭代器模式(Iterator)
c++·设计模式·rpc·迭代器模式·软件工程·uml
Carl_奕然2 天前
【智能体】Agent的四种设计模式之:React(2026最新版)
javascript·人工智能·python·react.js·设计模式·语言模型
cfm_29142 天前
Spring核心设计模式
java·spring·设计模式
今天会营业2 天前
单例模式:饿汉和懒汉
单例模式