java - How to avoid type-checking of a subclass? -
i have code:
public abstract class character { public abstract void attack(character victim); public abstract void receiveattack(attack attack); } public class charactera extends character { public void attack(character victim) { if (victim.getclass().equals(this.getclass()) return; victim.receiveattack(new attack(base_dmg)); } }
the idea character can attack , receiveattacks to/from other characters, cannot receive attack comes character of own class (charactera cannot attack charactera attack characterb or receive attack characterb).
i know checking type of object bad smell , caused because of bad design, question how change design don't have check object type?
edit
the class not named character
, name simplify example.
there no teams. charactera
can attack other character
not charactera
.
final edit
thanks everyone, solved using visitor pattern.
a simple solution/ work-around have 1 class, , every character
object has string
field named characterteam
or of like. characters on team, set field "a"
or "ateam"
. b team, set field "b"
or "bteam"
. compare characterteam
string
s in attack
method.
also, advise against having class named character
might interfere wrapper class char
, named character
.
Comments
Post a Comment