I can not understand why to use Context module(which we will see in the following codes) in strategy design pattern, what its function? Let's see one part of the strategy design pattern.
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 codes above, we may call different algorithms by this way:
Context context = new Context(new OperationAdd());
context.executeStrategy(10,5);
which I can not understand completely, why could not call the child class directly but to use the Context layer. In my opinion, simply like this:
Strategy addStrategy = new OperationAdd();
addStrategy.doOperation(10, 5);
Aucun commentaire:
Enregistrer un commentaire