Java中的五種單例模式實現方法

來源:互聯網
上載者:User

標籤:

[代碼] Java中的五種單例模式實現方法  
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 package singleton; /** * @author lei * 單例模式的五種寫法: * 1、懶漢 * 2、惡漢 * 3、靜態內部類 * 4、枚舉 * 5、雙重校正鎖 * 2011-9-6 *//** *五、 雙重校正鎖,在當前的記憶體模型中無效 */class LockSingleton{    private volatile static LockSingleton singleton;    private LockSingleton(){}         //詳見:http://www.ibm.com/developerworks/cn/java/j-dcl.html    public static LockSingleton getInstance(){        if(singleton==null){            synchronized(LockSingleton.class){                if(singleton==null){                    singleton=new LockSingleton();                }            }        }        return singleton;    }     }/** * 四、枚舉,《Effective Java》作者推薦使用的方法,優點:不僅能避免多線程同步問題,而且還能防止還原序列化重新建立新的對象 */enum EnumSingleton{    INSTANCE;    public void doSomeThing(){    }}/** * 三、靜態內部類 優點:載入時不會初始化靜態變數INSTANCE,因為沒有主動使用,達到Lazy loading */class InternalSingleton{    private static class SingletonHolder{        private final static  InternalSingleton INSTANCE=new InternalSingleton();    }       private InternalSingleton(){}    public static InternalSingleton getInstance(){        return SingletonHolder.INSTANCE;    }}/** * 二、惡漢,缺點:沒有達到lazy loading的效果 */class HungrySingleton{    private static HungrySingleton singleton=new HungrySingleton();    private HungrySingleton(){}    public static HungrySingleton getInstance(){        return singleton;    }}/** * 一、懶漢,常用的寫法 */class LazySingleton{    private static LazySingleton singleton;    private LazySingleton(){    }    public static LazySingleton getInstance(){        if(singleton==null){            singleton=new LazySingleton();        }        return singleton;    }   }

Java中的五種單例模式實現方法

聯繫我們

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