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

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

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;
    }
}

 

posted @ 2018-01-06 16:53  我_会飞的鱼  阅读(139)  评论(0编辑  收藏  举报