我的印象是这段代码可以通过某种方式利用多态来更清晰,但我似乎无法找到一种正确的方法.我尝试使用访问者模式,但没有设法使用它.
具有开关的"Hero"类:
public class Hero {
private Equipment equipment = new Equipment();
// other fields
public void equipArmor(Armor armor) {
findCorrespondingArmorSlot(armor).equipItem(armor);
}
private ItemSlot findCorrespondingArmorSlot(Armor armor) {
switch (armor.getArmorType()) {
case SHIELD:
return equipment.offHand;
case BODY:
return equipment.body;
case HEAD:
return equipment.head;
case GLOVES:
return equipment.hands;
case BOOTS:
return equipment.feet;
case BELT:
return equipment.waist;
case AMULET:
return equipment.neck;
case RING:
return equipment.finger;
case TRINKET:
return equipment.special;
}
throw new NullPointerException();
}
public Equipment getEquipment() {
return equipment;
}
// other …Run Code Online (Sandbox Code Playgroud)