1. 程式人生 > 其它 >Java設計模式---單例模式

Java設計模式---單例模式

概念:

  所謂類的單例設計模式,就是採取一定的方法保證在整個的軟體系統中,對某個類只能存在一個物件例項,並且該類只能提供一個取得其物件例項的方法(靜態方法)。

單例設計模式8中方式:

  • 餓漢式(靜態常量)
    • 步驟如下:
      • 構造器私有化(防止new)
      • 類的內部建立物件
      • 向外暴露一個靜態的公共方法。getInstance
      • 程式碼實現
        • package com.atguigu.singleton.type1;
          public class SingletonTest01 {
              public static void main(String[] args) {
                  //測試
                  Singleton instance = Singleton.getInstance();
                  Singleton instance2 
          = Singleton.getInstance(); System.out.println(instance == instance2); // true System.out.println("instance.hashCode=" + instance.hashCode()); System.out.println("instance2.hashCode=" + instance2.hashCode()); } } //餓漢式(靜態變數) class Singleton { //1. 構造器私有化, 外部能new private
          Singleton() { } //2.本類內部建立物件例項 private final static Singleton instance = new Singleton(); //3. 提供一個公有的靜態方法,返回例項物件 public static Singleton getInstance() { return instance; } }
      • 優缺點:
        • 優點:這種寫法比較簡單,就是在類裝載的時候就完成例項化。避免了執行緒同步問題。
        • 缺點:在類裝載的時候就完成例項化,沒有達到Lazy Loading的效果。如果從開始至終從未使用過這個例項,則會造成記憶體的浪費。
        • 這種方式基於classloader機制避免了多執行緒的同步問題,不過,instance在類裝載時就例項化,在單例模式中大多數都是呼叫getInstance方式,但是導致類裝載的原因有很多,因此不能確定有其他的方式(或其他的靜態方法)導致類裝載,這時候初始化instance就沒有達到lazy loading的效果。
        • 結論:這種單例模式可用,可能造成記憶體浪費。
  • 餓漢式(靜態程式碼塊)
    • 程式碼實現:
      • package com.atguigu.singleton.type2;
        
        public class SingletonTest02 {
        
            public static void main(String[] args) {
                //測試
                Singleton instance = Singleton.getInstance();
                Singleton instance2 = Singleton.getInstance();
                System.out.println(instance == instance2); // true
                System.out.println("instance.hashCode=" + instance.hashCode());
                System.out.println("instance2.hashCode=" + instance2.hashCode());
            }
        }
        
        //餓漢式(靜態變數)
        
        class Singleton {
            //1. 構造器私有化, 外部能new
            private Singleton() {
            }
            
        
            //2.本類內部建立物件例項
            private  static Singleton instance;
            static { // 在靜態程式碼塊中,建立單例物件
                instance = new Singleton();
            }
            
            //3. 提供一個公有的靜態方法,返回例項物件
            public static Singleton getInstance() {
                return instance;
            }
        }
    • 優缺點:
      • 優點:這種方式和上面的方式其實類似,只不過將類似例項化的過程放在了靜態程式碼塊中,也是在類裝載的時候,就執行靜態程式碼塊中的程式碼,初始化類的例項。優缺點和上面是一樣的。
      • 缺點:這種單例模式可用,但是可能造成記憶體浪費。
  • 懶漢式(執行緒不安全)
    • 程式碼實現:
      • package com.atguigu.singleton.type3;
        
        public class SingletonTest03 {
        
            public static void main(String[] args) {
                System.out.println("懶漢式1 , 執行緒不安全~");
                Singleton instance = Singleton.getInstance();
                Singleton instance2 = Singleton.getInstance();
                System.out.println(instance == instance2); // true
                System.out.println("instance.hashCode=" + instance.hashCode());
                System.out.println("instance2.hashCode=" + instance2.hashCode());
            }
        }
        
        class Singleton {
            private static Singleton instance;
            
            private Singleton() {}
            
            //提供一個靜態的公有方法,當使用到該方法時,才去建立 instance
            //即懶漢式
            public static Singleton getInstance() {
                if(instance == null) {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    • 優缺點:
      • 優點:
        • 起到了LazyLoading的效果,但是隻能在單執行緒下使用。
      • 缺點:
        • 如果在多執行緒下,一個執行緒進入了if(singleton == null)判斷語句塊,還未來得及往下執行,另一個執行緒也通過了這個判斷語句,這時便會產生多個例項。所以在多執行緒環境下不可使用這種方式。
  • 懶漢式(執行緒安全,同步方法)
    • 程式碼實現:
      • package com.atguigu.singleton.type4;
        
        public class SingletonTest04 {
        
            public static void main(String[] args) {
                System.out.println("懶漢式2 , 執行緒安全~");
                Singleton instance = Singleton.getInstance();
                Singleton instance2 = Singleton.getInstance();
                System.out.println(instance == instance2); // true
                System.out.println("instance.hashCode=" + instance.hashCode());
                System.out.println("instance2.hashCode=" + instance2.hashCode());
            }
        }
        
        // 懶漢式(執行緒安全,同步方法)
        class Singleton {
            private static Singleton instance;
            
            private Singleton() {}
            
            //提供一個靜態的公有方法,加入同步處理的程式碼,解決執行緒安全問題
            //即懶漢式
            public static synchronized Singleton getInstance() {
                if(instance == null) {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    • 優缺點:
      • 優點:
        • 解決了執行緒不安全問題
      • 缺點:
        • 效率太低了,每一個執行緒在想獲得類的例項時候,執行getInstance()方法都要進行同步。其實這個方法只執行一次例項化程式碼就夠了,後面的想獲得該類例項,直接return就行了。方法同步效率太低了。  
  • 雙重檢查
    • 程式碼實現
      • package com.atguigu.singleton.type6;
        public class SingletonTest06 {
        
            public static void main(String[] args) {
                System.out.println("雙重檢查");
                Singleton instance = Singleton.getInstance();
                Singleton instance2 = Singleton.getInstance();
                System.out.println(instance == instance2); // true
                System.out.println("instance.hashCode=" + instance.hashCode());
                System.out.println("instance2.hashCode=" + instance2.hashCode());
                
            }
        }
        
        // 懶漢式(執行緒安全,同步方法)
        class Singleton {
            private static volatile Singleton instance;
            
            private Singleton() {}
            
            //提供一個靜態的公有方法,加入雙重檢查程式碼,解決執行緒安全問題, 同時解決懶載入問題
            //同時保證了效率, 推薦使用
            
            public static synchronized Singleton getInstance() {
                if(instance == null) {
                    synchronized (Singleton.class) {
                        if(instance == null) {
                            instance = new Singleton();
                        }
                    }
                }
                return instance;
            }
        }
    • 優缺點:
      • 優點:
        • Double-Check概念是多執行緒開發中常使用到的,如程式碼中所示,我們進行了兩次if(singleton == null)檢查,這樣就可以保證執行緒安全了。
        • 這樣,例項化程式碼只用執行一次,後面再次訪問時,判斷if(singleton == null),直接return例項化物件,也避免了反覆進行方法同步。
        • 執行緒安全:延遲載入,效率較高
        • 結論:在實際開發中,推薦使用這種單例設計模式。
  • 靜態內部類
    • 程式碼實現:
      • package com.atguigu.singleton.type7;
        
        public class SingletonTest07 {
            public static void main(String[] args) {
                System.out.println("使用靜態內部類完成單例模式");
                Singleton instance = Singleton.getInstance();
                Singleton instance2 = Singleton.getInstance();
                System.out.println(instance == instance2); // true
                System.out.println("instance.hashCode=" + instance.hashCode());
                System.out.println("instance2.hashCode=" + instance2.hashCode());
            }
        }
        
        // 靜態內部類完成, 推薦使用
        class Singleton {
            private static volatile Singleton instance;
            //構造器私有化
            private Singleton() {}
            //寫一個靜態內部類,該類中有一個靜態屬性 Singleton
            private static class SingletonInstance {
                private static final Singleton INSTANCE = new Singleton(); 
            }
            
            //提供一個靜態的公有方法,直接返回SingletonInstance.INSTANCE
            
            public static synchronized Singleton getInstance() {
                return SingletonInstance.INSTANCE;
            }
        }
    • 優缺點:
      • 優點:
        • 這種方式採用了類裝載的機制來保證初始化例項時只有一個執行緒。
        • 靜態內部類方式在Singleton類裝載時並不會立即例項化,而是在需要例項化時,呼叫getInstance方法,才會裝載SingletonInstance類,從而完成Singleton的例項化。
        • 類的靜態屬性只會在第一次載入類的時候初始化,所以在這裡,JVM幫助我們保證了執行緒的安全性,在類進行初始化時,別的執行緒是無法進入的。
        • 避免了執行緒不安全,利用靜態內部類特點實現延遲載入,效率高
        • 結論:推薦使用。
  • 列舉
    • 程式碼實現:
      • package com.atguigu.singleton.type8;
        
        public class SingletonTest08 {
            public static void main(String[] args) {
                Singleton instance = Singleton.INSTANCE;
                Singleton instance2 = Singleton.INSTANCE;
                System.out.println(instance == instance2);
                
                System.out.println(instance.hashCode());
                System.out.println(instance2.hashCode());
                
                instance.sayOK();
            }
        }
        
        //使用列舉,可以實現單例, 推薦
        enum Singleton {
            INSTANCE; //屬性
            public void sayOK() {
                System.out.println("ok~");
            }
        }
    • 優缺點:
      • 優點:
        • 這藉助JDK1.5中新增的列舉來實現單例模式。不僅能避免多執行緒同步問題,而且還能防止反序列化重新建立新的物件。
        • 推薦使用
  • 單例模式注意事項和細節說明
    • 單例模式保證了系統內部中該類只存在一個物件,節省了系統資源,對於一些需要頻繁 建立銷燬的物件,使用單例模式可以提高系統性能。
    • 當想例項化一個單例類的時候,必須要記住使用相應的獲取物件的方法,而不是使用new
    • 單例模式使用的場景:需要頻繁的進行建立和銷燬的物件、建立物件時耗時過多(即:重量級物件),但又經常用到的物件、工具類物件、頻繁訪問資料庫或檔案的物件(比如資料來源、session工廠等)