继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

单例模式

Sivel
关注TA
已关注
手记 16
粉丝 9
获赞 50

夫子说过:“我不是世人所说的无所不能,我比划两下能让他懂便好,语言终究是细枝末节。”

设计模式便是通用的“比划动作”。这篇先讲一下单例模式。单例模式一般分为三种 饿汉 懒汉 枚举,其他都是变形。

懒汉模式: 线程是不安全的
加上 synchronized 就可以安全了 但是性能下降了

优点:第一次调用才初始化,避免内存浪费。

缺点:必须加锁 synchronized 才能保证单例,但加锁会影响效率。
public class Singleton {

private static Singleton ingleton;

public static Singleton getInstance() {
    if (ingleton != null) {
        ingleton = new Singleton();
    }
    return ingleton;
   }
}

饿汉式: 线程安全
优点:没有加锁,执行效率会提高。
缺点:类加载时就初始化,浪费内存。

public class Singleton {
      private static Singleton ingleton = new Singleton() ;

      public static Singleton getInstance() {

             return ingleton;
    }
}

3:双检锁
这种方式采用双锁机制,安全且在多线程情况下能保持高性能。
getInstance() 的性能对应用程序很关键。

public class Singleton {  
     private volatile static Singleton singleton;  
     private Singleton (){}  
     public static Singleton getSingleton() {  
        if (singleton == null) {  
           synchronized (Singleton.class) {  
           if (singleton == null) {  
                  singleton = new Singleton();  
    }  
    }  
}  
return singleton;  
   }  
}  

4:枚举

public enum SomeThing {
     INSTANCE;
   private Resource instance;
   SomeThing() {
        instance = new Resource();
  }
public Resource getInstance() {
    return instance;
  }
}
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP