简体   繁体   English

Java-具有泛型的工厂和策略模式

[英]Java - Factory and Strategy Patterns with Generics

I'm trying to implement a Strategy + Factory pattern using generics. 我正在尝试使用泛型实现Strategy + Factory模式。 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. 目标是将可以处理类型T扩展Document的DocumentDao接口的实现返回给客户端类,因此我具有多个Dao接口,用于针对Document的不同子类型扩展DocumentDao。

Here is my code: 这是我的代码:

public class Document { ... }

public class DocumentA extends Document { ... }

public class DocumentB extends Document { ... }

public interface DocumentDao<T extends Document> {
   public void update(T document);
}

public interface DocumentADao<DocumentA> {}

public interface DocumentDaoFactory {
   public <T extends Document> DocumentDao<T> getDaoInstance(Class<T> clazz);
}

Then I try to use the Factory: 然后,我尝试使用Factory:

private <T extends Document> void someMethod(T document) {
   ...
   DocumentDao<T> documentDao = this.documentDaoFactory.getDaoInstance(document.getClass());
   documentDao.update(document);
   ...
}

But the compiler complaints about the getDaoInstance() call: 但是编译器抱怨getDaoInstance()调用:

Type mismatch: cannot convert from DocumentDao<? extends AbstractGDriveDocument<?>> to DocumentDao<T>

How to deal with this situation? 如何处理这种情况? How can I obtain a similar solution? 如何获得类似的解决方案?

Thanks 谢谢

The problem is that getClass is returning a Class<?> , which is appropriate for the API; 问题在于getClass返回的Class<?> ,适合于API; it would not know what specific Class instance to bring back. 它不知道要带回哪个特定的Class实例。 Additionally, your type bound is incorrect and invalid in your method. 此外,您的类型绑定不正确,并且在您的方法中无效。

To fix this, you would need to change two things: 要解决此问题,您需要更改两件事:

  • In your DocumentDaoFactory method, change the bound to be appropriate. 在您的DocumentDaoFactory方法中,将绑定更改为适当的值。

     <T extends Document> DocumentDao<T> getDaoInstance(Class<T> clazz); 
  • In your use of getDaoInstance , perform an unchecked cast to Class<T> . 在使用getDaoInstance ,对Class<T>进行未经检查的强制转换。

     DocumentDao<T> documentDao = this.documentDaoFactory.getDaoInstance((Class<T>) document.getClass()); 

The way that your types are bound should give you back the instances you care about, without getting any runtime errors. 类型绑定的方式应该可以让您找回自己关心的实例,而不会出现任何运行时错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM