我正在实施战略模式:
public interface Stuff<T> {
T getStuff();
}
public class IntegerStuff implements Stuff<Integer> {
public Integer getStuff() { .. }
}
public class StringStuff implements Stuff<String> {
public String getStuff() { .. }
}
现在,我想使用“上下文”来设置策略并执行策略方法:
public class Context() {
private Stuff stuff;
public setStrategy(Stuff stuff) { this.stuff = stuff; }
public Object doStuff() { // ARGH!
return stuff.getStuff()
}
}
如何使用泛型,以便Context类的doStuff()
方法的类型可以与使用的策略类型相同?
答案 0 :(得分:3)
您还希望参数化Context
:
public class Context<T> {
private Stuff<T> stuff;
public setStrategy(Stuff<T> stuff) { this.stuff = stuff; }
public T doStuff() { // ARGH!
return stuff.getStuff()
}
}