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

一.什么是单例模式

一个类对应一个对象

二.特点

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);
    }
}
相关推荐
阿闽ooo3 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4963 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃3 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式
驴儿响叮当20103 天前
设计模式之状态模式
设计模式·状态模式
电子科技圈3 天前
XMOS推动智能音频等媒体处理技术从嵌入式系统转向全新边缘计算
人工智能·mcu·物联网·设计模式·音视频·边缘计算·iot
徐先生 @_@|||3 天前
安装依赖三方exe/msi的软件设计模式
设计模式
希望_睿智4 天前
实战设计模式之访问者模式
c++·设计模式·架构
茶本无香4 天前
设计模式之十六:状态模式(State Pattern)详解 -优雅地管理对象状态,告别繁琐的条件判断
java·设计模式·状态模式
驴儿响叮当20104 天前
设计模式之备忘录模式
设计模式·备忘录模式
驴儿响叮当20104 天前
设计模式之迭代器模式
设计模式·迭代器模式