設(shè)計(jì)模式之:?jiǎn)卫J?/h2>

實(shí)現(xiàn)單例應(yīng)該注意以下4點(diǎn):

  1. 構(gòu)造函數(shù)不對(duì)外開(kāi)放,一般為private;
  2. 通過(guò)一個(gè)靜態(tài)方法或者枚舉返回單例類(lèi)對(duì)象;
  3. 確保單例的對(duì)象有且僅有一個(gè),尤其是在多線(xiàn)程環(huán)境下;
  4. ?單例類(lèi)對(duì)象在反序列化時(shí)不會(huì)被重新構(gòu)建對(duì)象。

1. 餓漢單列模式

public class Singleton {
    private static Singleton instance= new Singleton();
    private Singleton() {};
    public static Singleton getInstance() {
        return instance;
    }
}

2. 懶漢單列模式

public class Singleton {
    private Singleton() {};
    private static Singleton instance= null;
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

3. 懶漢單列模式(雙重校驗(yàn))

public class Singleton {
    private Singleton() {};
    private static Singleton instance= null;
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.this){
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

4. 靜態(tài)內(nèi)部類(lèi)單列模式

public class Singleton {
    private Singleton() {};
    public static Singleton getInstance () {
        return SingletonHolder.instance;
    }
    private static class SingletonHolder {
        private static final Singleton instance = new Singleton();
    }
}

5. 枚舉單列模式

public enum Singleton {
    INSTANCE;
}

6. 容器實(shí)現(xiàn)單列模式

public class Singleton {
    private Singleton() {};
    private static Map<String, Object> objects = new HashMap<String, Object>();
    public static void registe (String key, Object instance) {
        if (!objects.containsKey(key)) objects.put(key, instance);
    }
    public static Object get () {
        return objects.get(key);
    }
}

注:。。。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容