- 單例模式的五種實現方式
- 發布時間:2016/1/11 來源:搜數網絡 瀏覽:25
單例模式可以說是23中設計模式中應用最廣的一種模式了。
定義:確保某一個類只有一個實例,自行實例化并且想整個系統提供這個實例。
使用場景:避免某個類產生多個對象而消耗過多的資源,確保某個類在程序中只有一個實例。比如我們使用的圖片加載器ImageLoader。往往單例創建的對象,耗費的資源都比較多,所以在初始化單例對象的時候就顯得尤為重要了,接下來,我們就來聊一聊單例的幾種實現方式。
一、餓漢式
- public class ImageLoader{
- private static ImageLoader instance = new ImageLoader;
- private ImageLoader(){}
- public static ImageLoader getInstance(){
- return instance;
- }
- }
二、懶漢式
- public class ImageLoader{
- private static ImageLoader instance;
- private ImageLoader(){}
- public static synchronized ImageLoader getInstance(){
- if(instance == null){
- instance = new ImageLoader();
- }
- return instance;
- }
- }
三、Double CheckLock實現單例
英文稍好點的東西,應該都看懂了,DCL也就是雙重鎖判斷機制,直接上代碼。
- public class ImageLoader{
- private static ImageLoader instance;
- private ImageLoader(){}
- public static ImageLoader getInstance(){
- if(instance == null){
- synchronized (ImageLoader.class){
- if(instance == null){
- instance = new ImageLoader();
- }
- }
- }
- return instance;
- }
- }
四、靜態內部類實現模式
直接上代碼
- public class ImageLoader{
- private static class InnerInstance{
- private static final ImageLoader instance = new ImageLoader();
- }
- private ImageLoader(){}
- public static ImageLoader(){
- return InnerInstance.instance;
- }
- }
可以發現這種方式,并未加鎖,因為第一次加載ImageLoader類時,并不會實例化單例對象,只有第一次調用getInstance()方法時會導致虛擬機加載InnerInstance類,這種
方式不僅能保證對象的單一性,還避免加鎖帶來的性能問題,又啟動了延遲加載的優化,所以這就是單例模式的終極實現版本,也是推薦使用的方式。
原文地址:http://blog.csdn.net/soul_code/article/details/50183765