【設計模式】—— 單例模式Singleton

  前言:【模式總覽】——————————by xingoohtml

  模式意圖

  保證類僅有一個實例,而且能夠供應用程序全局使用。爲了保證這一點,就須要這個類本身建立本身的對象,而且對外有公開的調用方法。函數

  模式結構

  Singleton 單例類,內部包含一個自己的對象。而且構造方法時私有的。spa

  使用場景

  當類只有一個實例,並且能夠從一個固定的訪問點訪問它時。code

  代碼結構

  【餓漢模式】經過定義Static 變量,在類加載時,靜態變量被初始化。htm

 1 package com.xingoo.eagerSingleton;
 2 class Singleton{
 3     private static final Singleton singleton = new Singleton();
 4     /**
 5      * 私有構造函數
 6      */
 7     private Singleton(){
 8         
 9     }
10     /**
11      * 得到實例
12      * @return
13      */
14     public static Singleton getInstance(){
15         return singleton;
16     }
17 }
18 public class test {
19     public static void main(String[] args){
20         Singleton.getInstance();
21     }
22 }

 

  【懶漢模式】對象

 1 package com.xingoo.lazySingleton;
 2 class Singleton{
 3     private static Singleton singleton = null;
 4     
 5     private Singleton(){
 6         
 7     }
 8     /**
 9      * 同步方式,當須要實例的纔去建立
10      * @return
11      */
12     public static synchronized Singleton getInstatnce(){
13         if(singleton == null){
14             singleton = new Singleton();
15         }
16         return singleton;
17     }
18 }
19 public class test {
20     public static void main(String[] args){
21         Singleton.getInstatnce();
22     }
23 }
相關文章
相關標籤/搜索