Suppose I am modelling different animals in Java. Every animal has some combination of these abilities: walk, swim and fly. For the example, the ability set is constant.
I can store this information as getters that return constants. For example:
public class Penguin implements Animal {
public boolean canWalk() {
return true;
}
public boolean canSwim() {
return true;
}
public boolean canFly() {
return false;
}
// implementation...
}
The run-time check is then:
if (animal.canFly()) {
// Fly!
}
Or I can use "tagging" interfaces:
public class Penguin implements Animal, Flyer, Swimmer {
// implementation...
}
The run-time check is then:
if (animal instanceof Flyer) {
// Fly!
}
What are the advantages and disadvantages of each approach?
Aucun commentaire:
Enregistrer un commentaire