java - Can I get rid of this switch and enum? -
i under impression piece of code cleaner somehow utilizing polymorphism, can't seem find proper way of doing it. tried using visitor pattern didn't manage far it.
the "hero" class has switch:
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 methods public class equipment { public itemslot mainhand = new itemslot(); public itemslot offhand = new itemslot(); public itemslot body = new itemslot(); public itemslot head = new itemslot(); public itemslot hands = new itemslot(); public itemslot feet = new itemslot(); public itemslot waist = new itemslot(); public itemslot neck = new itemslot(); public itemslot finger = new itemslot(); public itemslot special = new itemslot(); } }
and other stuff:
public class itemslot { private static final miscellaneous empty = new miscellaneous(); private item item = empty; public item getitem() { return item; } public void equipitem(item item) { unequipitem(); this.item = item; } public void unequipitem() { if (!isempty()) { item.addtoinventory(); item = empty; } } public boolean isempty() { return (item == empty); } } public abstract class item { // fields public void addtoinventory() { // code } // other methods } public class miscellaneous extends item{} public class armor extends item { private armortype type; public armortype getarmortype() { return type; } //other methods } public enum armortype { shield, body, head, gloves, boots, amulet, ring, belt, trinket; }
try following:
public enum armortype { shield(){ public itemslot getarmorslot(equipment equipment){ return equipment.offhand; } }, ... public abstract itemslot getarmorslot(equipment equipment); }
then call:
itemslot armorslot = armor.getarmortype().getarmorslot(equipment);
Comments
Post a Comment