I always tend to run into the following design problem that I'm never quite sure how to best resolve. It usually starts with a hierarchy of Animals at my Circus:
Animal
Cat
BigCat
Dog
Elephant
...
Now, each Animal needs to be trained, so that there is a separate method for each:
public interface Trainer {
void train( BigCat animal );
void train( Dog animal );
void train( Elephant animal );
// ...
}
The problem is that the CircusDirector doesn't give a damn. He just throws Animals to the Trainer without even looking.
public class CircusDirector {
public void work() {
Trainer trainer = getTrainer();
Animal animal = getAnimal();
// ...and he doesn't know a frog from a pony,
// so he tries to just:
trainer.train(animal);
}
}
Now, the Trainer can get an additional method like
void train( Animal animal );
where he'll use instanceof
to send the animal to the appropriate method, but this seems ugly and doesn't come recommended. Is there a better solution using generics?