完美的單例模式建立

來源:互聯網
上載者:User

標籤:style   blog   http   color   for   art   ar   問題   

  今天把設計模式拿出來看了下,發現以前對於單例模式的理解很是膚淺,沒考慮安全執行緒,在考慮了安全執行緒的情況下又沒考慮效能,當然我遇到的系統都不怎麼考慮並發效能,所以其實也無所謂,當看到單例模式的時候,上網搜尋了下,發下一片很好的文章,我把其中的單例模式整理了下,給了個結果出來。

  文章地址:http://blog.csdn.net/zhangerqing/article/details/8194653

  前提都是在考慮安全執行緒的情況下,可以有兩種情況。分別是懶漢式和餓漢式的一種實現。

  1.效能不太好,每次鎖對象,當然如果你遇到的跟我遇到的系統都一樣不考慮效能問題,其實這麼做也沒問題,但是不好。正如Oracle進階編程裡面所說的那樣,你的sql能正確的完成任務,但並不代表他能很好的完成任務。

  2.我們只希望在第一次getInstance的時候去執行個體化對象,這個就做到了,並且安全執行緒,但是如果類載入的時候出問題還是有可能出問題,所以借用那篇文章裡說的,要完成完美的實現是不可能的,我們只能根據實際情況來選擇合適的方式。

  1.直接鎖整個對象,保證安全執行緒,但是由於每次擷取都會鎖對象,效能不好,也不是我們希望的。

package singlePattern;/** * Thread safe single pattern, but performance is poor, because every time we will lock the instance, * we hope lock the instance on first time but all times *  * @author Administrator *  */public class SinglePattern {    // private instance    private static SinglePattern instance = null;    // private constructor    private SinglePattern() {    }    // public getInstance method    public synchronized static SinglePattern getInstance() {        if (instance == null) {            instance = new SinglePattern();        }        return instance;    }}

  2.我們需要的情形是在第一次初始化需要同步,之後的調用就不需要考慮線程同步。由於JVM在載入類的時候是互斥的,我們知道類載入器在載入類的時候會直接把靜態變數和靜態代碼塊執行一次,然後再去去調用普通代碼快,然後去調用構造方法初始化堆,然後在返回引用賦值給棧裡面的引用。於是我們可以利用類載入的靜態變數和靜態代碼塊來安全的構造單例執行個體。

  

package singlePattern;/** * Thread safe and performance good. * @author Administrator * */public class UserSinglePattern {        // private constructor    private UserSinglePattern() {}        // static inner class, for create a single pattern instance    private static class NewInstance {        private static UserSinglePattern instance = new UserSinglePattern();    }        // the get method for single pattern instance    public static UserSinglePattern getInstance() {        return NewInstance.instance;    }}

再貼下我參考的地址對作者表示感謝:http://blog.csdn.net/zhangerqing/article/details/8194653

  

聯繫我們

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