我正在尝试创建一个为 instanceof 对象Visitor<T>
返回某个值的对象。strategy
它已经有效,但我无法获得Generics
类型安全。我在以下代码中缺少什么:
class Base;
class Foo extends Base;
class Bar extends Base;
interface Visitor<T> {
T visit (Foo foo);
T visit (Bar bar);
}
interface Strategy<T> {
void action(T obj);
}
class FooStrategy implements Strategy<Foo> {
@Override
void action(Foo foo) {
//perform strategy action on foo
}
}
//References to generic type Strategy<T> should be parameterized
class MyVisitor implements Visitor<Strategy> {
//References to generic type Strategy<T> should be parameterized
@Override
Strategy visit(Foo foo) {
return new FooStrategy();
}
//References to generic type MyStrategy<T> should be parameterized
@Override
Strategy visit(Bar bar) {
return new BarStrategy();
}
}
在类MyVisitor
eclipse 中不断抱怨Strategy<T>
应该参数化。制作这个通用构造我缺少什么typesafe
?
更新:
我想像这样使用它:
Visitor<Strategy> visitor = new MyVisitor();
Strategy strat = drawable.accept(visitor);
//use the strategy
Base object; //may be a Foo or Bar or whatever
strat.action(object);