0

在此处输入图像描述

上图取自工厂方法示例,右上角的叉号表示它不是正确的解决方案。所以我想出了我自己的:

亚军.java

package test;

public class Runner {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Fighter f = new Fighter();
        f.attack();
        Wizard w = new Wizard();
        w.attack();
    }

}

播放器.java

package test;

public abstract class Player {
    protected String type;

    public Player(String type) {
        this.type = type;
    }
    public void attack() {
        WeaponFactory.getWeapon(type).hit();
    }
}

战斗机.java

package test;

public class Fighter extends Player {

    public Fighter() {
        super("Fighter");
    }

}

向导.java

包装测试;

public class Sword implements Weapon {

    public Sword() {
    }

    public void hit() {
        System.out.println("Hit by sword");
    }

}

武器.java

package test;

public abstract class Weapon {

    public void hit(){};

}

魔杖.java

包装测试;

public class Wand extends Weapon {

    public Wand() {
    }

    public void hit() {
        System.out.println("Hit by Wand");
    }

}

剑.java

包装测试;

public class Sword extends Weapon {

    public Sword() {
    }

    public void hit() {
        System.out.println("Hit by sword");
    }

}

武器工厂.java

包装测试;

public class WeaponFactory {


    public static Weapon getWeapon(String type) {
        Weapon returnValue = null;
        if(type.equals("Wizard")) {
            returnValue = new Wand();
        }else if(type.equals("Fighter")) {
            returnValue = new Sword();
        }
        return returnValue;
    }

}

我在使用工厂方法设计模式方面做得对吗

4

2 回答 2

0

查看此链接,我认为您的代码还可以。

尽管您可以简单地返回武器工厂中的新对象。

public class WeaponFactory {


    public static Weapon getWeapon(String type) {

        if(type.equals("Wizard")) {
            return new Wand();
        }else if(type.equals("Fighter")) {
            return new Sword();
        }

    }

}
于 2013-06-10T07:20:54.787 回答
0

你的 WeaponFactory 违反了开闭原则。为了符合面向对象的设计,请考虑以下更改:

public abstract class Player {
    protected WeaponFactory weaponFactory;

    public Player(WeaponFactory weaponFactory) {
        this.weaponFactory = weaponFactory;
    }
    public void attack() {
        weaponFactory.getWeapon().hit();
    }
}

public class Fighter extends Player {
    public Fighter() {
        super(new SwordFactory());
    }
}

public interface WeaponFactory {
    Weapon getWeapon();
}

创建实现 WeaponFactory 的 SwordFactory 和 WandFactory。

于 2013-06-10T11:33:27.643 回答