[英]How to avoid an unchecked cast with java and generics in strategy pattern
I have a coding pattern in java which is some flavor of the strategy pattern. 我在java中有一个编码模式,它是策略模式的一些风格。 My problem is that the code requires an unchecked cast which I would like to avoid.
我的问题是代码需要一个未经检查的强制转换,我想避免。 To explain it briefly, I firstly have a set of classes which share a common interface:
为了简要解释一下,我首先有一组共享一个通用接口的类:
interface IType {}
class TypeA implements IType {}
class TypeB implements IType {}
Then I have a set of strategies which do some specific processing on IType objects. 然后我有一套策略,它们对IType对象进行一些特定的处理。
interface IStrategy<T extends IType> {
specificProcessing(T o);
}
Lastly, I have a singleton which does some generic processing on ITypes, then fetches the proper IStrategy to do the specific processing. 最后,我有一个单例,它对ITypes进行一些通用处理,然后获取适当的IStrategy来进行特定的处理。 The IStrategy objects are registered in map and I think the method signature ensures that only matching pairs of ITypes and IStrategies go into the map.
IStrategy对象在map中注册,我认为方法签名确保只有匹配的IType和IStrategies对进入地图。
class Context {
private Map<Class<? extends IType>, IStrategy<? extends IType>> map;
public static Context getInstance() {}
public <T extends IType> void register(IStrategy<T> s, Class<T> c) {
map.put(c, s);
}
public <T extends IType> void genericProcessing(T o) {
//do generic stuff with o
@SuppressWarnings("unchecked")
IStrategy<T> s = (IStrategy<T>) map.get(o.getClass());
s.specificProcessing(o);
}
}
The "problem" is the unchecked cast warning. “问题”是未经检查的投射警告。 I know this happens because the declaration of the map allows non-matching pairs of IType and IStrategy.
我知道这是因为地图的声明允许不匹配的IType和IStrategy对。 I also know that the code is type safe because of register().
我也知道代码是类型安全的,因为register()。 But is there any other design which avoids the unchecked cast?
但有没有其他设计可以避免未经检查的演员?
I would appreciate any input, thanks. 我要感谢任何意见,谢谢。
There is no way to avoid it when using this map. 使用此地图时无法避免它。 I would suggest moving the map access into a separate method, so the code reads more cleanly.
我建议将地图访问移动到一个单独的方法,以便代码读得更干净。
@SuppressWarnings("unchecked")
private <T extends IType> IStrategy<T> getStrategy(T o) {
return (IStrategy<T>) map.get(o.getClass());
}
BTW, you can do it in scala. 顺便说一下,你可以用scala来做。
Edit: 编辑:
You can do it in Octarine , see blog on post Extractors . 您可以在Octarine中进行 ,请参阅post Extractors上的博客 。 But maybe this is just a fancy way or moving the logic to it's own method, but bringing in a lot of complexity.
但也许这只是一种奇特的方式或将逻辑转移到它自己的方法,但带来了很多复杂性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.