Vaguely about a strategy design pattern

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);
+3
source share
3 answers

Although I did not like this example, I will explain the benefits of using context.

Context . , - Factory.

Context, Factory_Method, Strategy, Input. if else .

, executeStrategy, .

Context . Add Subtract 100 , .

Context, , , , .

: Strategy_Pattern . , , ( : /)

Strategy, :

+1

, , . .

5 15 . .

+2

, . , , , .

, .

, , , if-else . .

When dependency injection is in the picture, then scenarios of specific concrete strategy options can be inserted at runtime. So, the container performing this dependency injection began to play the role of Context.

0
source

Source: https://habr.com/ru/post/1664459/


All Articles