Can you explain strategy pattern?

Strategy pattern are algorithms inside a class which can be interchanged depending on the class used. This pattern is useful when you want to decide on runtime which algorithm to be used.
Let’s try to see an example of how strategy pattern works practically. Let’s take an example of a math’s calculation where we have strategies like add and substract. Figure ‘Strategy in action’ shows the same in a pictorial format. It takes two numbers and the depending on the strategy it gives out results. So if it’s an addition strategy it will add the numbers, if it’s a subtraction strategy it will give the substracted results. These strategies are nothing but algorithms. Strategy pattern are nothing but encapsulation of algorithms inside classes.

Figure: – Strategy in action

So the first thing we need to look in to is how these algorithms can be encapsulated inside the classes. Below figure ‘Algorithm encapsulated’ shows how the ‘add’ is encapsulated in the ‘clsAddStatergy’ class and ‘substract’ in the ‘clsSubstractStatergy’ class. Both these classes inherit from ‘clsStratergy’ defining a ‘calculate’ method for its child classes.

Figure: – Algorithms encapsulated

Now we define a wrapper class called as ‘clsMaths’ which has a reference to the ‘clsStatergy’ class. This class has a ‘setStatergy’ method which sets the strategy to be used.

Figure: – Strategy and the wrapper class

Below figure ‘Strategy client code’ shows how the wrapper class is used and the strategy object is set on runtime using the ‘setStatergy’ method.

Figure: – Strategy client code

Tagged , , . Bookmark the permalink.

Leave a Reply