设计模式-单例模式

    xiaoxiao2021-04-12  36

    单例模式(Singleton Pattern)是一个比较简单的模式,其定义“确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例”。 UML: 实现:

    /** * 懒汉式单例模式 */ public class Singleton2 { private static Singleton2 instance = null; /* 限制产生多个对象 */ private Singleton2(){ } /** * 方法上加synchronized修饰,保证线程安全,同时也会影响性能 * @return */ public static synchronized Singleton2 getInstance(){ if (null == instance){ instance = new Singleton2(); } return instance; } } /** * 饿汉式单例模式 */ public class Singleton1 { /** * JVM加载时创建实例 */ private static Singleton1 instance = new Singleton1(); /* 限制产生多个对象 */ private Singleton1(){ } public static Singleton1 getInstance(){ return instance; } } /** * double check单例模式实现 */ public class Singleton { //使用volatile关键字保其可见性 volatile private static Singleton instance = null; private Singleton() { } public static Singleton getInstance() { try { if (instance != null) {//首次检查 } else { synchronized (Singleton.class) { if (instance == null) {//二次检查 instance = new Singleton(); } } } } catch (InterruptedException e) { e.printStackTrace(); } return instance; } }

    参考资料: 《设计模式之禅(第2版)》

    转载请注明原文地址: https://ju.6miu.com/read-667117.html

    最新回复(0)