title: Java - Factory and Strategy Patterns with Generics
body: <p>I'm trying to implement a Strategy + Factory pattern using generics. The goal is to return to a client class an implementation of the interface DocumentDao that can deal with a type T extends Document, so I've multiple Dao interface extending DocumentDao for different subtypes of Document.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>public class Document { ... }
  
  public class DocumentA extends Document { ... }
  
  public class DocumentB extends Document { ... }
  
  public interface DocumentDao&lt;T extends Document&gt; {
     public void update(T document);
  }
  
  public interface DocumentADao&lt;DocumentA&gt; {}
  
  public interface DocumentDaoFactory {
     public &lt;T extends Document&gt; DocumentDao&lt;T&gt; getDaoInstance(Class&lt;T&gt; clazz);
  }
  </code></pre>
  
  <p>Then I try to use the Factory:</p>
  
  <pre><code>private &lt;T extends Document&gt; void someMethod(T document) {
     ...
     DocumentDao&lt;T&gt; documentDao = this.documentDaoFactory.getDaoInstance(document.getClass());
     documentDao.update(document);
     ...
  }
  </code></pre>
  
  <p>But the compiler complaints about the getDaoInstance() call:</p>
  
  <pre><code>Type mismatch: cannot convert from DocumentDao&lt;? extends AbstractGDriveDocument&lt;?&gt;&gt; to DocumentDao&lt;T&gt;
  </code></pre>
  
  <p>How to deal with this situation?
  How can I obtain a similar solution?</p>
  
  <p>Thanks</p>