首页 > 其他 > 详细

设计模式-单例模式

时间:2019-10-15 01:35:15      阅读:92      评论:0      收藏:0      [点我收藏+]

单例模式

饿汉式(急切实例化)

public class EagerSingleton {

    /** 1.私有化构造方法 */
    private EagerSingleton() {
    }
    
    /** 2.声明静态成员变量并赋初始值-类初始化的时候静态变量就被加载,因此叫做饿汉式 */
    public static EagerSingleton eagerSingleton=new EagerSingleton();

    /** 3.对外暴露公共的实例化方法 */
    public static EagerSingleton getInstance(){
        return eagerSingleton;
    }
    
}

懒汉式(延迟实例化)(DCL双重检测)

  -为什么要判断两次?  

    避免由于并发导致的线程安全问题

  -为什么要使用 volatile关键字修饰 ourInstance?

    避免指令重排序,同时保证变量ourInstance在线程之间是可见的

public class LazySingleton {

    /** 1.私有化构造方法 */
    private LazySingleton() {
    }

    /** 2.声明静态变量 -这里声明为volatile,是禁止指令重排序 */
    private volatile static LazySingleton ourInstance;

    /** 3.对外暴露公共的实例化方法 */
    public static LazySingleton getInstance() {

        if (ourInstance == null) {
            synchronized (LazySingleton.class) {
                if (ourInstance == null) {
                    ourInstance = new LazySingleton();
                }
            }
        }
        return ourInstance;
    }

}

 

设计模式-单例模式

原文:https://www.cnblogs.com/gabriel-y/p/11675012.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!