單例設計模式 (代碼實現)

來源:互聯網
上載者:User

標籤:

 

  ---單例設計模式之餓漢式---

 

  建立SingleInstance類

 1 /** 2  * 單例設計模式之餓漢式 3  */ 4 public class SingleInstance {     5     /** 6      * 私人化構造方法 7      */ 8     private SingleInstance() {} 9     /**10      * 成員變數11      */12     private static SingleInstance instance = new SingleInstance() ;13     /**14      * 提供一個靜態成員方法,返回該對象15      */16     public static SingleInstance getInstance() {17         return instance ;18     }19 }

 

  建立測試類別SingleInstanceDemo

 

 1 /** 2  * 單例設計模式的思想:    保證該類在記憶體中只有一個執行個體(對象) 3  * 優點節省記憶體,提高記憶體利用率 4  */ 5 public class SingleInstanceDemo { 6      7     public static void main(String[] args) { 8          9         // 調用方法擷取對象10         SingleInstance instance1 = SingleInstance.getInstance() ;11         SingleInstance instance2 = SingleInstance.getInstance() ;12         13         // 輸出14         System.out.println(instance1 == instance2);15     }16 }

 

 

-------------------------------------------------------------------------------------------------------------

 

  ---單例設計模式之懶漢式---

 

  建立SingleInstance2類

 1 /** 2  * 單例設計模式之懶漢式 3  *  4  * 面試中寫那種單例設計模式呢? 5  *         面試中寫懶漢式:    因為懶漢式體現了兩種思想, 第一種線程問題 , 第二種 消極式載入 6  *  7  *    開發中寫餓漢式 8  */ 9 public class SingleInstance2 {10     /**11      * 私人化構造方法12      */13     private SingleInstance2() {}14     /**15      * 提供一個成員變數16      */17     private static SingleInstance2 instance = null ;18     /**19      * 提供一個靜態成員方法20      */21     public static synchronized SingleInstance2 getInstance() {22     23         if(instance == null){24             instance = new SingleInstance2() ;25         }26         return instance ;27     }28 }

 

  建立測試類別SingleInstanceDemo2

 

 1 public class SingleInstance2Demo { 2      3     public static void main(String[] args) { 4          5         // 擷取對象 6         SingleInstance2 instance1 = SingleInstance2.getInstance() ; 7         SingleInstance2 instance2 = SingleInstance2.getInstance() ; 8          9         // 比較10         System.out.println(instance1 == instance2);11         12     }13 14 }

 

單例設計模式 (代碼實現)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.