重温设计模式之原型模式

用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

如果玩过魔兽争霸3都知道剑圣有一个技能叫镜像,分裂出两个和自身属性一样的假剑圣,只是没有攻击力。

考虑一下创建假剑圣的过程,剑圣有等级、力量、敏捷、智力等可变属性,如果用new的方式创建,则需要把每个属性重新设置一遍。

BladeMaster fake1 = new BladeMaster();
fake1.setLevel(origin.getLevel());
fake1.setStr(origin.getStr());
fake1.setDex(origin.getDex());
fake1.setIntelligence(origin.getIntelligence());
fake1.setAttack(0);

如何更简单的创建对象,避免设置属性的过程?克隆。

修改后的代码:

public class BladeMaster implements Cloneable {

    private int level;
    private int str;
    private int dex;
    private int intelligence;
    private int attack;

    public BladeMaster() {
    }

    public BladeMaster(int level, int str, int dex, int intelligence, int attack) {
        this.level = level;
        this.str = str;
        this.dex = dex;
        this.intelligence = intelligence;
        this.attack = attack;
    }

    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return String.format("[lvl: %d, str: %d, dex: %d, int: %d, atk: %d]", level, str, dex, intelligence, attack);
    }

    //getter/setter略
}
    public static void main(String[] args) throws CloneNotSupportedException {

        BladeMaster bladeMaster = new BladeMaster(5, 55, 80, 30, 100);
        System.out.println(bladeMaster.toString());

        BladeMaster mirror1 = (BladeMaster)bladeMaster.clone();
        mirror1.setAttack(0);
        System.out.println(mirror1.toString());

        BladeMaster mirror2 = (BladeMaster)bladeMaster.clone();
        mirror2.setAttack(0);
        System.out.println(mirror2.toString());
    }

上述过程虽然只是调用了clone方法,但是已经是应用了原型模式,可以说是最简单的设计模式了。

你可能感兴趣的:(Java开发)