Reputation: 857
I'm implementing the Strategy Pattern:
public interface Stuff<T> {
T getStuff();
}
public class IntegerStuff implements Stuff<Integer> {
public Integer getStuff() { .. }
}
public class StringStuff implements Stuff<String> {
public String getStuff() { .. }
}
Now, I want to use a "Context" to set the strategy and execute the strategy method:
public class Context() {
private Stuff stuff;
public setStrategy(Stuff stuff) { this.stuff = stuff; }
public Object doStuff() { // ARGH!
return stuff.getStuff()
}
}
How can I use generic, so that the type of the doStuff()
method on the Context class, can be of the same type as the used strategy?
Upvotes: 2
Views: 3678
Reputation: 81114
You would want to parameterize Context
as well:
public class Context<T> {
private Stuff<T> stuff;
public setStrategy(Stuff<T> stuff) { this.stuff = stuff; }
public T doStuff() { // ARGH!
return stuff.getStuff()
}
}
Upvotes: 7