[设计模式]单例模式的懒汉式写法

一.什么是单例模式

一个类对应一个对象

二.特点

2.1唯一的对象在外界调用方法来获取这个唯一对象的时候才创建的

2.2有线程安全问题

2.3没安全性的写法

复制代码
public class SingleOne{
    private static SingleOne instance;
    private SingleOne() {};

    /*public synchronized static SingleOne getInstance() {
        if (instance == null) {
            instance = new SingleOne();
        }
        return instance;
    }*/

    public static SingleOne getInstance() {
        if (instance == null) {
            synchronized (SingleOne.class) {
                if (instance == null) {
                    instance = new SingleOne();
                }
            }
        }
        return instance;
    }
}

含内部类的

复制代码
public class SingleFive {
/*    static {
        System.out.println("外部类的静态代码块");
    }*/

    private SingleFive(){//构造器私有化
//        System.out.println("外部类的构造器");//new对象是执行
    }

    public static SingleFive getInstance(){
        return Inner.instance;
    }

    private static class Inner{
        static SingleFive instance = new SingleFive();
       /* static {
            System.out.println("内部类的静态代码块");
        }*/
    }
/*
    public static void method(){
        System.out.println("外部类的普通的静态方法");
    }*/
}

三.写法要求

复制代码
public class SingleOne {
    private static SingleOne instance;
    private SingleOne() {};

    public static SingleOne getInstance() {
        if (instance == null) {
            instance = new SingleOne();
        }
        return instance;
    }
}
复制代码
import org.junit.jupiter.api.Test;

public class TestSingleOne {
    @Test
    public void test() {
        SingleOne s1 = SingleOne.getInstance();
        SingleOne s2 = SingleOne.getInstance();
        System.out.println(s1 == s2);
    }
}
相关推荐
日和雫9 小时前
封装、继承、多态 & 组合,为什么组合大于继承?
设计模式
代钦塔拉12 小时前
【C++/Qt 进阶】设计模式系列(6):桥接模式——把“两个独立变化的维度“拆开
c++·qt·设计模式
haluhalu.12 小时前
深入理解AIAgent(1.3)--- 设计模式
人工智能·python·设计模式·langchain
高晶1 天前
CANopen 在 BMS 系统中的 C 语言实战指南
设计模式·程序员
博风1 天前
13、设计模式应用举例:工厂方法模式:创建药品对象
设计模式·工厂方法模式
代钦塔拉2 天前
【C++/Qt 进阶】设计模式系列(5):适配器模式——给“不兼容的接口“贴一层翻译膜
c++·qt·设计模式
bigbread2 天前
策略模式 + 工厂方法模式在项目中的实战应用
设计模式
高晶2 天前
C 语言实现 BMS 系统中 SPI 通信协议实战指南
设计模式·程序员
代钦塔拉2 天前
【C++/Qt 进阶】设计模式系列(2):工厂模式——从游戏角色到披萨店
c++·算法·设计模式
高晶2 天前
2A3 单端甲类功放从零制作全攻略:电路设计、焊接调试到煲机维护一站式指南
前端·设计模式