【设计模式】单例设计模式

1、单例设计模式之饿汉式

 1 public class Singleton {
 2 
 3     // 将自身实例化对象设置为一个属性,并用static、final修饰
 4     private static final Singleton instance = new Singleton();
 5     
 6     // 构造方法私有化
 7     private Singleton() {}
 8     
 9     // 静态方法返回该实例
10     public static Singleton getInstance() {
11         return instance;
12     }
13 }

2、单例设计模式之懒汉式

 1 public class Singleton {
 2 
 3     // 将自身实例化对象设置为一个属性,并用static修饰
 4     private static Singleton instance;
 5     
 6     // 构造方法私有化
 7     private Singleton() {}
 8     
 9     // 静态方法返回该实例
10     public static Singleton getInstance() {
11         // 第一次检查instance是否被实例化出来,如果没有进入if块
12         if(instance == null) {
13             synchronized (Singleton.class) {
14                 // 某个线程取得了类锁,实例化对象前第二次检查instance是否已经被实例化出来,如果没有,才最终实例出对象
15                 if (instance == null) {
16                     instance = new Singleton();
17                 }
18             }
19         }
20         return instance;
21     }
22 }

完结。。。

posted @ 2021-03-08 23:49  程序不程序  阅读(54)  评论(0编辑  收藏  举报