上記の図はファクトリ メソッドの例から抜粋したもので、右隅の十字は、それが適切なソリューションではないことを示しています。だから私は自分自身を思いついた:
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();
}
}
ファイター.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");
}
}
武器.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");
}
}
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;
}
}
ファクトリ メソッドの設計パターンを使用するという点で、私はそれを正しく行いましたか?