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

一.什么是单例模式

一个类对应一个对象

二.特点

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);
    }
}
相关推荐
Java成神之路-1 小时前
从 if-else 到优雅解耦:策略 / 适配器 / 组合模式全流程实战
设计模式
是2的10次方啊9 小时前
设计模式与生活⑰:空腹体检,单子领着人走
设计模式
是2的10次方啊1 天前
设计模式与生活⑯:天冷了,出门这身得一层层配
设计模式
心若自由何处是束缚2 天前
适配器模式:从原理到实战的完整指南
设计模式·适配器模式
是2的10次方啊2 天前
设计模式与生活⑮:看到哪儿了,得有个地方替你记着
设计模式
2601_967979123 天前
设计模式 - 访问者模式
设计模式·访问者模式·应用场景·对象结构·操作分离
是2的10次方啊3 天前
设计模式与生活⑭:一栋楼,共用一份热
设计模式
是2的10次方啊4 天前
设计模式与生活⑬:你坐几号线,谁来运营是另一回事
设计模式
Tt有了t5 天前
设计模式速查
java·python·设计模式
一条Go5 天前
四个进程,一把锁:Alioth 的告警评测为什么不需要消息队列
后端·设计模式·架构