首页 > 其他 > 详细

23种设计模式学习之单例模式

时间:2018-01-06 17:39:00      阅读:170      评论:0      收藏:0      [点我收藏+]

用内部类来维护单例的实现

public class Singleton {
  //私有构造方法,防止被实例化 private Singleton(){}
  //用一个内部类来维护单例 private static class SingletonFactory{ private static Singleton singleton=new Singleton(); }
  //获取实例 public static Singleton getInstance(){ return SingletonFactory.singleton; } }

 使用锁实现单例

public class Singleton {
    private static Singleton singleton=null;
    private Singleton(){}
    private static synchronized void syncInit() {
        if (singleton == null) {
            singleton = new Singleton();
        }
    }
    public static Singleton getInstance(){
        if (singleton == null){
            syncInit();
        }
        return singleton;
    }
}

 

23种设计模式学习之单例模式

原文:https://www.cnblogs.com/2nao/p/8214657.html

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