上图取自工厂方法示例,右上角的叉号表示它不是正确的解决方案。所以我想出了我自己的:
亚军.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;
}
}
我在使用工厂方法设计模式方面做得对吗