title: Create different Objects with same base type. Factory pattern?
body: <p>I have to implement a multiple producers / multiple consumers example application for a university course and have a hard time to find a solution for the following problem, that doesn't make me feel, that I do something wrong ;)</p>
  
  <p>I have to implement a <code>Producer</code> which produces a given kind of <code>Component</code> (<code>CPUComponent</code>, <code>MainboardComponent</code>. All subclasses of a common <code>Component</code> class). Each instance of a <code>Producer</code> will only produce a given amount of one type of component (e.g. only Mainboards) and then quits.</p>
  
  <p>The <code>Component</code>s are all more or less immutable objects (only <code>final</code> fields) and all logic is implemented in the common base class <code>Component</code> (simplified below)</p>
  
  <pre><code>public abstract class Component implements Serializable
  {    
      private final long id;
  
      public Component(int id) { ... }
  
      public long getId()
      {
          return id;
      }
  }
  </code></pre>
  
  <p>The subclasses of <code>Component</code> are merely primitive, like</p>
  
  <pre><code>public class CPUComponent extends Component
  {
      public CPUComponent(long id) { ... }
  }
  </code></pre>
  
  <p>With the language being Java, I cannot solve this object generation easily with <strong>Generics</strong> (as I would be able to in C#, because I cannot instantiate new objects of generic type parameters in Java). So I started to implement a <strong>Factory</strong></p>
  
  <pre><code>public interface ComponentFactory {
      Component createComponent(Producer producer, boolean defective);
  }
  </code></pre>
  
  <p>And provide concrete factory implementations for each <code>Component</code> type.</p>
  
  <p>The problem I have now is that, when I want to store the produced components in my <code>Storage</code> class (just manages all produced components for the consumers), I need to figure out the exact type of the objects (every <code>CPUComponent</code>, etc. in it's own shelf), but I only get a <code>Component</code> (base type) from the factory.</p>
  
  <p>So the only thing that would help now, would be <code>instanceof</code>, but I think there has to be a better solution for my problem.</p>
  
  <p>The other solution I can think of would be to implement a <code>Producer</code>s for each type of <code>Component</code>, but I wanted to avoid that way.</p>
  
  <p>Maybe I'm thinking way to complex and have already completely over-engineered the whole thing. Just point me in the right direction ;)</p>