[设计模式]单例模式饿汉式写法

一.什么是单例模式

一个类对应一个对象

二.特点

唯一对象在类初始化的时候就new好了

eg:

2.1第一种写法

复制代码
public class SingleOne {
    //在类的内部提前创建好这个类的唯一对象
    private static final SingleOne singleOne = new SingleOne();
    //其他成员正常定义
//    private int a;

    //构造器私有化,不允许外部创建对象
    private SingleOne(){
        ;
    }

    //供外界获取这个类的唯一对象
    public static SingleOne getSingleOne(){
        return singleOne;
    }

    //其他成员正常定义
}
复制代码
import org.junit.jupiter.api.Test;

public class TestSingleOne {
    @Test
    public void testSingleOne(){
        SingleOne singleOne = SingleOne.getSingleOne();
        SingleOne singleOne1 = SingleOne.getSingleOne();
        System.out.println(singleOne == singleOne1);
    }
}

2.2第二种写法

复制代码
public class SingleOneAnotherWriteModel {
    public static final SingleOneAnotherWriteModel singleOneAnotherWriteModel
            = new SingleOneAnotherWriteModel();;
    //其他成员正常定义

    //构造器私有化
    private SingleOneAnotherWriteModel(){
        ;
    }

    //其他成员正常定义
}
复制代码
import org.junit.jupiter.api.Test;

public class TestSingleOneAnotherWriteModel {
    @Test
    public void testSingleOneAnotherWriteModel(){
        SingleOneAnotherWriteModel singleOne = SingleOneAnotherWriteModel.singleOneAnotherWriteModel;
        SingleOneAnotherWriteModel singleOne1 = SingleOneAnotherWriteModel.singleOneAnotherWriteModel;
        System.out.println(singleOne == singleOne1);
    }
}

三.特点

饿汉式写法没有线程安全问题

相关推荐
杨充14 小时前
11.DDD与战术建模
设计模式·开源·代码规范
杨充14 小时前
12.综合实战图片框架
设计模式·开源·代码规范
芝士熊爱编程19 小时前
创建型模式-单例模式
java·单例模式·设计模式
咖啡八杯21 小时前
GoF设计模式——访问者模式
设计模式·访问者模式
谢栋_1 天前
设计模式从入门到精通之(七)责任链模式
java·设计模式·责任链模式
葬送的代码人生2 天前
别再让 AI 瞎写代码了!Vibe Coding 三步法教你写出靠谱代码
前端·设计模式·架构
无风听海2 天前
Claude Agent Skills 的四种设计模式;从渐进式披露到最小权限
java·算法·设计模式
富贵冼中求2 天前
从单向流到双向 RPC:Agent 通信协议的范式分叉与 ACP 协议实战拆解
设计模式·架构
电子科技圈2 天前
先进封装、芯粒架构和3D集成——先进异构集成亟需兼具标准化与定制化能力的互联及总线IP解决方案
tcp/ip·设计模式·架构·软件构建·代码规范·设计规范
zjun10012 天前
C++:2.工厂模式
设计模式