设计模式-单例模式

单例模式分为饿汉式、懒汉式

饿汉式:类加载时直接创建实例,类加载时已经生成示例,所以线程安全

java 复制代码
public class SingletonOne {

    //类加载时初始化示例
    private static SingletonOne instance = new SingletonOne();
    private SingletonOne(){};
    private static SingletonOne getInstance() {
        return instance;
    }

    public static void main(String[] args) {
        SingletonOne s1 = getInstance();
        SingletonOne s2 = getInstance();
        System.out.println(s1 == s2);//true
    }
}

懒汉式:用到实例的时候再创建,多线程场景下,创建出的实例可能不唯一,违反了单一实例原则

下方测试代码在多线程模式下,s1可能不等于s2

java 复制代码
public class SingletonTwo {

    private static SingletonTwo instance = null;
    private SingletonTwo(){};
    //用到实例时再创建
    private static SingletonTwo getInstance() {
        if(instance == null) {
            instance = new SingletonTwo();
        }
        return instance;
    }

    public static void main(String[] args) {
        SingletonTwo s1 = getInstance();
        SingletonTwo s2 = getInstance();
        System.out.println(s1 == s2);//true
    }
}
相关推荐
摇滚侠1 天前
Java 饿汉式 单例模式
java·开发语言·单例模式
游乐码2 天前
Unity坦克案例疑难记录(一)
unity·单例模式
想学会c++5 天前
单例模式笔记总结
c++·笔记·单例模式
是个西兰花5 天前
单列模式和C++中的类型转换
c++·单例模式·设计模式·rtti
nnsix5 天前
设计模式 - 单例模式 笔记
笔记·单例模式·设计模式
cui_ruicheng5 天前
Linux线程(四):线程池、日志系统与单例模式
linux·开发语言·单例模式
2301_815279526 天前
实战分享实现 C++ 管理类单例模式:特点与最佳实践
javascript·c++·单例模式
阿维的博客日记6 天前
细说DCL单例模式和volatile有什么关系,volatile在DCL中是必要的吗??
单例模式·synchronized·happens-before
c++之路6 天前
单例模式(Singleton Pattern)
开发语言·c++·单例模式
青山师7 天前
CompletableFuture深度解析:异步编程范式与源码实现
java·单例模式·面试·性能优化·并发编程