1)單例模式的定義:數據庫
在整個應用中,保證一個類只有一個實例,它提供了一個能夠訪問到它本身的全局訪問點(靜態方法)。安全
2)單例模式的優缺點:多線程
優勢:性能
一、提供了對惟一實例的受控訪問;spa
二、Java中頻繁建立和銷燬類對象都會佔用一部分系統資源,使用單例模式能夠提升性能;線程
三、容許可變數量的實例;設計
缺點:code
一、單例模式中,沒有抽象層,因此對於單例類的擴展並不方便;對象
二、單例類的職責太重,在必定程度上違背了「單一職責原則」;blog
三、濫用單例將帶來一些負面問題,如爲了節省資源將數據庫鏈接池對象設計爲的單例類,可能會致使共享鏈接池對象的程序過多而出現鏈接池溢出;若是實例化的對象長時間不被利用,系統會認爲是垃圾而被回收,這將致使對象狀態的丟失;
3)簡單介紹幾種單例,單例模式中有區分了懶漢式和餓漢式,懶漢式主要是用時間來換空間,餓漢式則是用空間來換時間。餓漢式是線程安全的,懶漢式是非線程安全的,若是要實現懶漢式的非線程安全,則能夠再訪問點添加synchronized關鍵字聲明便可。在其餘的一些項目中還使用了雙重檢測枷鎖機制。
一、懶漢單例,存在線程不安全問題,如啓動多線程,同時調用入口方法獲取實例時不能正常工做:
//懶漢單例,線程不安全,當啓動多線程,同時獲取多個實例時會報錯 private static PostContentForResponse instance = null; private PostContentForResponse() {} public static PostContentForResponse getInstance() { if(instance == null) { instance = new PostContentForResponse(); } return instance; }
懶漢模式也提供一種解決同步調用時不能正常工做的方法,使用synchronized聲明訪問點,可是工做效率低
private static PostContentForResponse instance = null; private PostContentForResponse() {} public static synchronized PostContentForResponse getInstance() { if(instance == null) { instance = new PostContentForResponse(); } return instance; }
二、餓漢單例,這種方式基於classloder機制避免了多線程的同步問題,可是instance在類裝載時就實例化,雖然致使類裝載的緣由有不少種,
在單例模式中大多數都是調用getInstance方法,可是也不能肯定有其餘的方法(或者其餘靜態方法)致使類裝載,這是初始化的instance
顯然沒有達到lazy loading的效果。
private static PostContentForResponse instance = new PostContentForResonse(); private PostContentForResponse() {} public static PostContentForResponse getInstance() { return instance; }
三、靜態內部類,跟餓漢模式有點相似,只是在類裝載的時候,SingletonHolder並無被主動使用,只有顯式調用getInstance方法是,纔會調用裝載SingletoHolder類,從而實例化instance,既實現了線程安全,又避免了同步帶來的性能影響。
private static class SingletonHolder { private static final PostContentForResponse INSTANCE = new PostContentForResponse(); } private PostContentForResponse() {} public static final PostContentForResponse getInstance() { return SingletonHolder.INSTANCE; }