C06 原型模式 示例(六) 原型模式破壞單例模式

原型模式對(duì)單例模式的破壞

  • 利用反射調(diào)用單例類的 clone() 方法,獲得單例類的多個(gè)實(shí)例;
public class HungrySingleton implements Cloneable{

    private final static HungrySingleton hungrySingleton;

    static {
        hungrySingleton = new HungrySingleton();
    }

    private HungrySingleton() {}

    public static HungrySingleton getInstance() {
        return hungrySingleton;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

}

public class Test {
    public static void main(String[] args) throws Exception{
        HungrySingleton hungrySingleton = HungrySingleton.getInstance();

        Method method = HungrySingleton.class.getDeclaredMethod("clone");
        method.setAccessible(true);
        HungrySingleton cloneHungrSingleton = (HungrySingleton)method.invoke(hungrySingleton);

        System.out.println(hungrySingleton);
        System.out.println(cloneHungrSingleton);
        System.out.println(hungrySingleton == cloneHungrSingleton);
    }
}

輸出:

designpattern.creational.prototype.singletonattack.HungrySingleton@5b6f7412
designpattern.creational.prototype.singletonattack.HungrySingleton@27973e9b
false

解決方案

  • 在 clone() 方法中直接調(diào)用 getInstance() 方法;
public class HungrySingleton implements Cloneable{

    private final static HungrySingleton hungrySingleton;

    static {
        hungrySingleton = new HungrySingleton();
    }

    private HungrySingleton() {}

    public static HungrySingleton getInstance() {
        return hungrySingleton;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return getInstance();
    }

}

public class Test {
    public static void main(String[] args) throws Exception{
        HungrySingleton hungrySingleton = HungrySingleton.getInstance();

        Method method = HungrySingleton.class.getDeclaredMethod("clone");
        method.setAccessible(true);
        HungrySingleton cloneHungrSingleton = (HungrySingleton)method.invoke(hungrySingleton);

        System.out.println(hungrySingleton);
        System.out.println(cloneHungrSingleton);
        System.out.println(hungrySingleton == cloneHungrSingleton);
    }
}

輸出:

designpattern.creational.prototype.singletonattack.HungrySingleton@5b6f7412
designpattern.creational.prototype.singletonattack.HungrySingleton@5b6f7412
true

?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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