I am following an example of strategy pattern from here
Everything in the tutorial 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);
}
}
So the Context class expects a Strategy argument in its constructor.
The definition of Strategy is:
public interface Strategy {
public int doOperation(int num1, int num2);
}
The above being an 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 utterly confused as we cant init an interface according to the definition:
An interface is different from a class in several ways, including:
You cannot instantiate an interface.
How exactly is this Context context = new Context(new OperationAdd());
sent as an argument to public Context(Strategy strategy){
this.strategy = strategy;
}
The classes OperationAdd
, OperationSubstract
and OperationMultiply
all implement the interface Strategy
. Therefore instances of those classes can be passed into the constructor of Context
which expects an object of type Strategy
.
As OperationAdd
, OperationSubstract
and OperationMultiply
implement the interface Strategy
, they are all of that type.
You are probably missing these lines, at the beginning of the example:
public class OperationSubstract implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
... // etc.
Here you can see that there are some "operation" classes that implement the Strategy interface. A class that implements an interface is basically an "actual instance" of that interface.
You may think this way, if it's clearer to you:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With