generics - Question about the design of dynamic subclass hierarchy handling -


I always like to run in the following design problem, I'm never quite sure how the best solution will be. It usually starts with a hierarchy of animals in my circus:

  animal cat BigCat dog elephant ...  

Now, every animal There is a need to train, so that there is a different method for each:

  Public Interface Trainer {Zero Train (Big Cat Animal); Zero train (dog animals); Zero train (elephant beast); // ...}  

The problem is that circus directors do not give a damn. He just throws the trainer to the animals without seeing them.

  Public Squared Circuit Director {Public Zero Work () {Trainer Trainer = Millinator (); Animal animal = meeting (); // ... and he does not know a frog from a pony, // so he just tries: trainer.train (animal); }}  

Now, the trainer can get an additional method such as

  zero train (animal animal);  

Where it will use instanceof to send the animal to the appropriate method, but it looks ugly and has not been recommended. What is a better solution using generic?

You essentially applied halfway

You can provide a sweet trailer (trainer T) method of each of your animals, then the t.train (this);

animal.acceptTrainer (trainer);

Also, I think the generic information is compiled, so you can not do any fancy stuff that you trust. It is best to be familiar with some samples.


Comments