手写设计模式

单例模式

饿汉式

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 禁止指令重排,先初始化再引用指向。
相关推荐
庞轩px14 小时前
第六篇:Spring用了哪些设计模式?——从单例到代理,拆解框架中的经典设计
java·spring·设计模式·bean·代理模式·aop·单例
多加点辣也没关系15 小时前
设计模式-工厂方法模式
设计模式·工厂方法模式
多加点辣也没关系19 小时前
设计模式-建造者模式
设计模式·建造者模式
多加点辣也没关系20 小时前
设计模式-桥接模式
设计模式·桥接模式
雪度娃娃1 天前
结构型设计模式——装饰模式
设计模式·装饰器模式
sensen_kiss1 天前
CPT304 SoftwareEngineeringII 软件工程 2 Pt.4 设计模式(下)
设计模式·软件工程
2301_815279521 天前
实战分享实现 C++ 管理类单例模式:特点与最佳实践
javascript·c++·单例模式
多加点辣也没关系1 天前
设计模式-适配器模式
设计模式
阿维的博客日记1 天前
细说DCL单例模式和volatile有什么关系,volatile在DCL中是必要的吗??
单例模式·synchronized·happens-before
Forget the Dream1 天前
基于适配器模式的 Axios 封装实践
设计模式·typescript·axios·适配器模式