Java设计模式——单例模式

   参考文章:https://www.jianshu.com/p/127903ae72b0

   作者:ghwaghon

   来源:简书

单例模式主要运用在类的实例化上面,有且仅有唯一的实例对象供我们操作,比如一台打印机,一台音乐播放器,根据经验知识我们在同一时间只允许操作一台设备。那么我们怎么来确保呢?

方法一、懒汉式(经典式)

 1 public class LazySingleton {
 2     private static LazySingleton lazyst= null;
 3     
 4     public LazySingleton() {
 5         
 6     }
 7     public static LazySingleton getInstance() {
 8         if (lazyst == null) {                      //但要有多个线程呢?这就是懒汉式的不足之处,如果用synchronized修饰方法来解决,多次调用的话十分消耗资源。
 9             lazyst= new LazySingleton();
10         }
11         
12         return lazyst;
13         
14     }
15     
16 }

 

    不足之处显而易见

 

方法二、饿汉式

 1 public class EagerSingleton {
 2 
 3     private static EagerSingleton eagerst= new EagerSingleton();
 4     private EagerSingleton() {
 5     }
 6     
 7     public EagerSingleton getInstance() {
 8         return eagerst;
 9     }
10 }

 

其弥补了懒汉式的缺点,但是直接实例化,倘若并不需要使用该类,将造成内存的浪费。

 

方法三、双重锁定检查法

 1 public class BetterSingleton1 {
 2     
 3     private static volatile BetterSingleton1 bs1= null;
 4     
 5     private BetterSingleton1() {
 6     }
 7     
 8     public BetterSingleton1 getInstance() {
 9         if (bs1 == null) {
10             synchronized (BetterSingleton1.class) {
11                 if (bs1 == null) {
12                     bs1= new BetterSingleton1();
13                 }
14             }
15         }
16         return bs1;
17         
18     }
19     
20 }

    由懒汉发展而来,但也同时弥补了饿汉的缺陷。

 

方法四、内部类方法

 1 public class BetterSingleton2 {
 2     private BetterSingleton2() {
 3         
 4     }
 5     
 6     public static BetterSingleton2 getInstance() {
 7         return CreatBetterSingleton2.bs2;
 8     }
 9     
10     private static class CreatBetterSingleton2{
11         private final static BetterSingleton2 bs2= new BetterSingleton2(); 
12     }
13 }

其中线程安全由JVM来保证(具体原理有待考究),而通过方法调用才生成实例对象避免了空间的浪费。

posted @ 2020-10-15 15:17  emperorChen  阅读(105)  评论(0)    收藏  举报