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

一.什么是单例模式

一个类对应一个对象

二.特点

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);
    }
}
相关推荐
忧郁的Mr.Li5 小时前
设计模式--工厂模式
设计模式
HL_风神7 小时前
C++设计模式浅尝辄止
c++·设计模式
会员果汁8 小时前
22.设计模式-享元模式(Flyweight)
设计模式·哈希算法·享元模式
小码过河.11 小时前
设计模式——访问者模式
设计模式·访问者模式
Engineer邓祥浩12 小时前
设计模式学习(21) 23-19 备忘录模式
学习·设计模式·备忘录模式
亓才孓13 小时前
[设计模式]单例模式饿汉式写法
单例模式·设计模式
代码丰13 小时前
设计模式:不再手动 set DTO,采用 Builder 模式
设计模式
老蒋每日coding14 小时前
AI Agent 设计模式系列(二十一)—— 探索和发现设计模式
人工智能·设计模式
春日见15 小时前
C++单例模式 (Singleton Pattern)
java·运维·开发语言·驱动开发·算法·docker·单例模式