lundi 26 octobre 2015

How to differenciate similar objects in Java without getClass()?

I am making a simple game un Java and I think I have a design problem. I have an abstract class Unit that have all units' behaviour (like move(), attack(), getHealth(), ...). Then I extend three classes from Unit: Archer, Lancer, Rider. Each one of those only have a constructor to differenciate them, because they behave exactly the same way but have different stats.

public class Archer extends Unit {    
    public Archer(World world, Location location, Player owner) {
        super(new Attack(1, 6, 1), new Defense(1, 4, 2), 10, 4, location, owner);
    }
}

public class Lancer extends Unit {    
    public Lancer(World world, Location location, Player owner){
        super(new Attack(2, 2, 5), new Defense(3,2,3), 15, 5, location, owner);
    }
}

public class Rider extends Unit{    
    public Rider(World world, Location location, Player owner) {
        super(new Attack(3, 2, 4), new Defense(2,4,1), 15, 7, location, owner);
    }
}

Now comes the problem. I want to be able to print those units with different sprites, so I make ArcherUI, LancerUI and RiderUI classes that have each sprite. But how do I tell the program to print for example an Archer?

A solution might be do a getClass() for every Unit, but it isn't a good one since I want a good object oriented design.

An other option that came into my mind was to add a name to the unit like that:

public class Archer extends Unit {  
    String name = "archer";
    public Archer(World world, Location location, Player owner) {
        super(new Attack(1, 6, 1), new Defense(1, 4, 2), 10, 4, location, owner);
    }
}

but then comparing this String would be the same as making a getClass(). What can I do? Is there any idea? or any pattern?

Aucun commentaire:

Enregistrer un commentaire