I follow the example of a strategy template from here
Everything in the textbook is clear, but this:
public class Context { private Strategy strategy; public Context(Strategy strategy){ this.strategy = strategy; } public int executeStrategy(int num1, int num2){ return strategy.doOperation(num1, num2); } }
Thus, the Context class expects a strategy argument in its constructor.
Strategy Definition:
public interface Strategy { public int doOperation(int num1, int num2); }
The above interface, the Context class expects an object of type Strategy. In the StrategyPatternDemo class, we do:
public class StrategyPatternDemo { public static void main(String[] args) { Context context = new Context(new OperationAdd()); System.out.println("10 + 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationSubstract()); System.out.println("10 - 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationMultiply()); System.out.println("10 * 5 = " + context.executeStrategy(10, 5)); } }
I am completely confused as we cannot initialize the interface as defined:
An interface differs from a class in several ways, including:
You cannot create an interface.
How exactly does this Context context = new Context(new OperationAdd()); sent as argument public Context(Strategy strategy){ this.strategy = strategy; } public Context(Strategy strategy){ this.strategy = strategy; }
source share