As usual, we are going to start with the abstraction, so here is our interface, our strategy interface,
which essentially has only one method DU operation, and it takes two parameters of type integer.
So you will see how we can modify at runtime the operation, the algorithm that is behind this operation.
So let's take a look first at the ad operation class that implements this strategy.
So basically this will have the addition operation behind.
So basically it will add the two numbers that are given as parameters to this method and multiply performance
multiplication.
And also we have substraction which performs substraction, of course.
So also, the next object that we are going to look into is this context object, which contains a strategy,
a reference to a strategy object.
And as you can see, we initialize it using this strategy.
We give in this constructor a strategy object and this strategy will be will be assigned this variable
over here, the execute strategy method will basically invoke that the operation method for this specific
strategy.
And as you can see, we make use of these two parameters, which will be further path to this to this
method over here.
And let's take a look at the app class and the main method here.
So basically we initialize to integers.
And as you can see here, we need to create a context object, which we need to initialize it with a
specific implementation of this strategy.
And here we called execute strategy method that will add in our case.
In the first case, it will add the two numbers together.
In the second example, we use the same variable and we initialize it with a multiply operation.
So this essentially, when we call execute strategy, will multiply these two numbers over here.
So let's run this and see this in action.
So as you can see, we get 12, which is the result of this, which is correct.
And 20, which is the result of the second operation.
So this is what I mean when I say that we change the algorithm at runtime.
So basically at runtime we can change the algorithm for this execute strategy as we want.
And also it is very easy to add other strategies we don't have to modify and we don't have to change
the existing code.
We just add another class, another concrete class that will implement the strategy and we will perform
our operation here.
We will write whatever algorithm we want inside this new operation method.
That's it for this story.
You'll join me in the next one when we are going to discuss about the template method design pattern.