I was reading about the Strategy design pattern here.
They used one interface called strategy that contains one function called doOperation
public interface Strategy {
public int doOperation(int num1, int num2);
}
Then they build two classes OperationAdd and OperationSubstract that implement this strategy interface
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;
}
}
After this, they defined a class called Context that contains private strategy interface and the constructor receives a strategy and fills it in the private attribute. Moreover, they did a function that calls the function of the strategy interface.
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);
}
}
Finally, they did the final class called StrategyPatternDemo that called the Context class.
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));
}
}
I understood the concept of the strategy pattern. However, I didn't understand how we can pass the classes OperationAdd and OperationSubstract in the constructor of the Context class while it receives an interface. as shown in Context context = new Context(new OperationAdd()); and context = new Context(new OperationSubstract());
How the class is cast to the interface?
Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire