Populating a zoo object with animal objects using enum in Java
<p>Being used to old-school procedural C programming I am now learning Java and has come to the perhaps obvious insight that the hard bit is <em>design</em> and not syntax.</p>

<p>I have spent hours scrapping idea after idea of how to populate my zoo:</p>

<p>I have a <code>class Zoo</code> and and an abstract <code>class Animal</code>. There are several non-abstract subclasses of <code>Animal</code> called <code>Lion</code>, <code>Giraffe</code>, <code>Zebra</code>, <code>Penguin</code>, and so on. A <code>Zoo</code> object will contain exactly one instance of each subclass of <code>Animal</code>, and each such instance contains a reference to the unique <code>Zoo</code> instance it belongs to.</p>

<p>I would like to iterate over the animals at the zoo in a specific order (as you walk along a footpath say) as well as look up animals at the zoo in a dictionary. More precisely, at some point I am going to parse a text file containing animal names (e.g. for the string "LION" I want to get the unique <code>Lion</code> instance). There is a one-to-one mapping of strings to animals. I have settled on using <code>LinkedHashMap&lt;String, Animal&gt;</code>.</p>

<p>I want to write manageable code that enables me to easily add more animals in future. My best approach so far is as follows.</p>

<p>In the <code>Zoo</code> class I define an <code>enum</code> that reflects the ordering of the animals that I want, and its elements correspond exactly to the strings I will parse in the text file.</p>

<pre><code>private enum Species { LION, GIRAFFE, ZEBRA, PENGUIN };
</code></pre>

<p>In <code>Zoo</code> I also have a method that creates an animal object:</p>

<pre><code>private Animal makeAnimal(Species species)
{
    switch (species)
    {
        case LION:
            // create a Lion object;
            break;
        case GIRAFFE:
            // ...
    }
    // return the Animal object created above;
}
</code></pre>

<p>As part of the constructor of <code>Zoo</code> I iterate over the <code>enum</code> and insert elements into the <code>LinkedHashMap</code> called <code>animals</code>:</p>

<pre><code>for (Species species : Species.values())
    animals.put(species.name(), makeAnimal(species));
</code></pre>

<p>To add a new animal I have to</p>

<ol>
<li>add a subclass to <code>Animal</code>,</li>
<li>stick a new element into the <code>enum</code>,</li>
<li>add a case to the <code>switch</code> statement in the <code>makeAnimal(Species species)</code> method.</li>
</ol>

<p>Is this a sound and sane approach? Now after taking the time to write this question down I am actually rather happy with my approach ;), but perhaps I am missing an obvious <em>design pattern</em> and my solution will back-fire at some point. I have the feeling that there is an undesirable separation between the name <code>"LION"</code> and its <code>class Lion</code> that is not ideal.</p>