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

一.什么是单例模式

一个类对应一个对象

二.特点

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);
    }
}
相关推荐
qqxhb4 小时前
26|Agent 设计模式:ReAct、Plan-and-Solve 与反射
设计模式·react模式·plan-and-solve·reflection模式
hssfscv5 小时前
软件设计师下午题六——Java的各种设计模式
java·算法·设计模式
zhaoshuzhaoshu7 小时前
设计模式之创建型设计模式详细解析(含示例)
单例模式·设计模式·架构
梦游钓鱼8 小时前
c++中单例模式(局部静态变量)
开发语言·c++·单例模式
倚楼盼风雨8 小时前
浅析设计模式-23种设计模式剖析
设计模式
游乐码8 小时前
c#单例模式
单例模式·c#
Momentary_SixthSense1 天前
设计模式之工厂模式
java·开发语言·设计模式
Java码农也是农1 天前
Multi-Agent 系统设计模式
设计模式·agent·multi-agent
sg_knight1 天前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
workflower1 天前
深度学习是通用型人工智能的基础
人工智能·深度学习·设计模式·软件工程·软件构建·制造