简体   繁体   中英

Java, Strategy Pattern, Generics and return type

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?

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()
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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