Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This has Factory design pattern written all over it. You can register each Animal class (e.g. Cat, Fish, Dog, Bird, etc.) in their respective classes.</p> <p>See <strong>Class Registration - avoiding reflection</strong> on <a href="http://www.oodesign.com/factory-pattern.html" rel="nofollow">http://www.oodesign.com/factory-pattern.html</a></p> <p>You can have an AnimalFactory that keeps a map of ID to class that implements Facotry Method. Then you would register it in each specific implementation of Animal. This way AnimalFactory wouldn't need to change, just each new Animal that is added would need to register the specific factory:</p> <pre><code>public class Dog extends Animal { ... static { AnimalFactory.instance().registerAnimal(ID.DOG, new DogCreator()); } ... } public class DogCreator extends AnimalFactory { //Abstract factory method in AnimalFactory that gets called to return the Animal public Animal createAnimal { return new Dog(); } } </code></pre> <hr> <h2>Begin Edit</h2> <p>You can also have a generic Animal creator that uses reflection to make the new class (assuming each Animal has an empty constructor). This would still require you to register your specific id in each Animal implementation:</p> <pre><code>public class Dog extends Animal { ... static { AnimalFactory.instance().registerAnimal(ID.DOG, Dog.class); } ... } </code></pre> <p>Then AnimalFactory can use reflection to make the instance:</p> <pre><code>public Animal createAnimal(ID id) { return animalMap.get(id).newInstance(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload