使用Factory方法设计模式的正确方法是什么?

时间:2013-06-10 02:34:54

标签: factory-pattern design-patterns

enter image description here

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

Runner.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();
    }

}

Player.java

package test;

public abstract class Player {
    protected String type;

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

Fighter.java

package test;

public class Fighter extends Player {

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

}

Wizard.java

包裹测试;

public class Sword implements Weapon {

    public Sword() {
    }

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

}

Weapon.java

package test;

public abstract class Weapon {

    public void hit(){};

}

Wand.java

包裹测试;

public class Wand extends Weapon {

    public Wand() {
    }

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

}

Sword.java

包裹测试;

public class Sword extends Weapon {

    public Sword() {
    }

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

}

WeaponFactory.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;
    }

}

我是否在使用工厂方法设计模式

方面做得对

2 个答案:

答案 0 :(得分:0)

查看此link我认为您的代码没问题。

虽然你可以简单地在Weapon Factory中返回新对象。

public class WeaponFactory {


    public static Weapon getWeapon(String type) {

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

    }

}

答案 1 :(得分:0)

你的武器工厂违反了开放封闭原则。要符合面向对象的设计,请考虑以下更改:

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。