C06 原型模式 示例(六) 原型模式破坏单例模式

原型模式对单例模式的破坏

  • 利用反射调用单例类的 clone() 方法,获得单例类的多个实例;
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() 方法中直接调用 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值