單例設(shè)計(jì)模式筆記

記錄幾種單例模式寫法。

餓漢模式(線程不安全)

    /**
     * 餓漢模式(線程不安全)
     * @return
     */
    private static Singleton getInstanceHungry() {
        mInstance = new Singleton();
        return mInstance;
    }

懶漢模式(線程不安全)

     /**
     * 懶漢模式(線程不安全)
     * @return
     */
    private static Singleton getInstanceLazy() {
        if (mInstance == null) {
            mInstance = new Singleton();
        }
        return mInstance;
    }

懶漢鎖模式(線程安全)

    /**
     * 懶漢鎖模式(線程安全)
     *
     * @return
     */
    private synchronized static Singleton getInstanceLazyThreadSafetyOne() {
        if (mInstance == null) {
            mInstance = new Singleton();
        }
        return mInstance;
    }

懶漢雙重判斷模式(線程安全)

    /**
     * volatile 修飾作用
     * 1.防止重排序
     * 2.值改變通知其他線程可見
     */
    private static volatile Singleton mInstance;

    /**
     * 懶漢雙重判斷模式(線程安全)
     *
     * @return
     */
    private synchronized static Singleton getInstanceLazyThreadSafetyTwo() {
        if (mInstance == null) {
            synchronized (Singleton.class) {
                if (mInstance == null) {
                    mInstance = new Singleton();
                }
            }
        }
        return mInstance;
    }

靜態(tài)內(nèi)部類模式

    /**
     * 靜態(tài)內(nèi)部類模式
     */
    public static class SingletonHolder {
        private static volatile Singleton mInstance;
    }

    public static Singleton getInstanceInnerclass() {
        return SingletonHolder.mInstance = new Singleton();
    }

容器管理模式

    /**
     * 容器管理模式
     */

    private static Map<String, Object> mSingleMap = new HashMap<>();


    static {
        mSingleMap.put("activity_manager", new Singleton());
    }

    public static Object getService(String serviceName) {
        return mSingleMap.get(serviceName);
    }

注:定義 private static volatile Singleton mInstance 帶有 volatile 修飾主要是為了保證線程可見性和防止代碼重排序的問題。

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

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