設計模式 — 單例模式

來源:互聯網
上載者:User

單例模式
嗯, 我們來開始第4個模式 ---  單例模式
一.  我們首先來探討下單例模式存在的必要性
單例模式就是在系統裡面只有唯一的執行個體。所以許多人會說,在系統裡面一個對象只有一個執行個體我們並不是不能做到呀, 我們何必要單獨抽象出一個設計模式呢?比如,在java裡面我們可以用static關鍵字來申明一個變數 public static Student student = new Student();然後所有的程式員協定好,大家都只用這一個對象,不要再去new這個對象。這樣就實現了單例模式了。
的確。。, 我們確實可以這樣得到單例模式,不過這樣做如果Student對象初始化非常困難的話,這樣餓漢式初始化是非常耗費資源的。

二.  最初的設想
所以,聰明的你會想到一種得到單例模式的方法 --- 私人化建構函式, 然後提供公用的單例對象提供者。
代碼:
public class SingleInstance{
 private SingleInstance instance;
 private SingleInstance(){}
 
 public static getInstance(){
  if (instance == null){
   instance = new SingleInstance();
  }
  return instance;
 }
}
嗯。。確實是非常不錯的設計!我們可以實現懶漢式初始化和得到唯一的對象介面。下面我們來探討在多線程下面的單例模式。

 

三.  多線程下面的單例模式

我們繼續來研究上面那段代碼,它在單線程裡面運行一點問題沒有。但是如果在多線程下面,我們還可以得到我們唯一的對象嗎?

我們假設有兩個線程A, B, A剛好執行完代碼if (instance == null) ,還沒有執行new操作。然後B開始執行,這個時候instance 肯定是 null(因為沒有人執行 new SingleInstance()), 所以B會執行new SingleInstance(),A也會執行new SingleInstance()。這樣就和我們設計的初衷不相符了! 

 ok ... 我們會馬上想到解決的方法, 在JAVA裡面我們可以使用synchronized 同步關鍵字來解決多線程問題。 不錯, 我們可以這樣寫:

public class SingleInstance{
 private SingleInstance instance;
 private SingleInstance(){}
 
 public static synchronized SingleInstance getInstance(){
  if (instance == null){
   instance = new SingleInstance();
  }
  return instance;
 }
}

 

 四. 多線程下單例模式效能的問題

按照上面這段代碼, 我們繼續分析,有人肯定會馬上提出:用synchronized關鍵字不會導致效能問題嗎?答案是肯定的!

那我們如果解決效能問題呢?

我們可以採用雙重判斷的方法解決這個問題, 比如:

public class SingleInstance{
 private SingleInstance instance;

 Object lock = new Object();
 private SingleInstance(){}
 
 public static SingleInstance  getInstance(){
  if (instance == null){

   synchronized(lock){

        if (instance == null){

            instance = new SingleInstance();

        }

   }
 
  }
  return instance;
 }
}

這段代碼和上面那段代碼的優點就在於在進入synchronized程式碼片段之前就進行了一次有效判斷。所以,只有第一次建立這個對象的時候才會進入synchronized程式碼片段裡面。所以,有效提高了效率!

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.