單例模式,模式

來源:互聯網
上載者:User

單例模式,模式
懶漢式:

package org.burning.sport.design.pattern.singlepattern;/** * 單例模式----懶漢式,在第一次調用的時候執行個體化自己 * * (事實上,通過Java反射機制是能夠執行個體化構造方法為private的類的, * 那基本上會使所有的Java單例實現失效。此問題在此處不做討論,姑且掩耳盜鈴地認為反射機制不存在。) */public class Singleton {    //私人構造器,代表不能通過在外部new來建立對象    private Singleton(){}    private static Singleton singleton = null;    // 1.擷取執行個體的靜態Factory 方法(線程不安全的)    public static Singleton getInstance() {        if(singleton == null) {            singleton = new Singleton();        }        return singleton;    }    // 2.擷取執行個體的靜態Factory 方法(安全執行緒的)    public static synchronized Singleton getSafeInstance() {        if(singleton == null) {            singleton = new Singleton();        }        return singleton;    }    // 3.雙重檢查鎖定    public static Singleton getSafe2Instance() {        if(singleton == null) {            synchronized (Singleton.class) {                if(singleton == null) {                    singleton = new Singleton();                }            }        }        return singleton;    }    // 3. 這種擷取執行個體的方式比1,2都好,既實現了安全執行緒,有避免了同步帶來的效能影響    public static final Singleton getSafe3Instance() {        return LazyHolder.INSTANCE;    }    private static class LazyHolder {        private static final Singleton INSTANCE = new Singleton();    }}

 

餓漢式:
package org.burning.sport.design.pattern.singlepattern;/** * 單例模式----餓漢式單例 *  餓漢式在類建立的同時就已經建立好一個靜態對象供系統使用,以後不再改變,所以天生是安全執行緒的。 */public class Singleton2 {    private Singleton2(){}    private static final Singleton2 singleton = new Singleton2();    public static Singleton2 getInstance() {        return singleton;    }}

 https://gitee.com/play-happy/base-project

聯繫我們

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