I can’t understand why to use the context module (which we will see in the following codes) in the strategy design template, what is its function? Take a look at one part of the strategy design template.
public interface Strategy {
public int doOperation(int num1, int num2);
}
public class OperationAdd implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
public class OperationSubstract implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
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);
}
}
From the above codes, we can name different algorithms as follows:
Context context = new Context(new OperationAdd());
context.executeStrategy(10,5);
which I cannot fully understand why it was impossible to call the child class directly, but use a context layer. In my opinion, just like that:
Strategy addStrategy = new OperationAdd();
addStrategy.doOperation(10, 5);
source
share