Strategy Pattern

You might also like

You are on page 1of 1

Strategy Pattern Use strategy when you need to define a family of algorithms, encapsulate each on e, and make them

interchangeable. Strategy lets the algorithm vary independently from clients tha t use it. Related patterns include State, Flyweight, Decorator, and Composite. The Strategy pattern is much like the State pattern, but a little different in i ntent (aim). The Strategy pattern consists of a number of related algorithms encapsulated in a driver clas s called the Context. Your client program can select one of these differing algorithms or in some cases the Context might select the best one for you. The intent (aim), like the State pattern, is to switch easily between algorithms without any monolithic conditional statements. The difference between State and Strategy is that the user generally chooses whi ch of several strategies to apply and that only one strategy at a time is likely to be instantiated and a ctive within the Context class. But in state pattern it is likely that all of the different States will b e active at once and switching may occur frequently between them. In addition, Strategy encapsulates several al gorithms that do more or less the same thing, while State pattern encapsulates related classes that ea ch does something somewhat different. Finally, the concept of transition between different states is completely missing in the Strategy pattern. Strategy pattern are algorithms inside a class which can be interchanged dependi ng 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. We have str ategies like add and subtract. Following figure shows the same in a pictorial format. It takes two nu mbers 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 subtracted results. These strategies are n othing but algorithms. Strategy pattern are nothing but encapsulation of algorithms inside classes.

You might also like