Saturday, 28 April 2007

Strategy Design pattern

In today's class, we discussed one of the most important design pattern called strategy design pattern. Certainly there are some patterns that are more useful in programming terms compared to other patterns.
Strategy design pattern is whereby different algorithms can be selected on-the-fly at run time [1].

Difficult to understand, I know, well to put it in simple words strategy pattern, creates different algorithms used in an application, encapsulate them and make them interchangeable. Each algorithm is handled as a separate object. Strategy pattern lets the algorithm vary independent from the client.

Perhaps an example would make it more simpler; I would like to quote an example which all of us have used unknowingly that we are following strategy design pattern; [2]
All of us have worked with websites and created forms in it. While making a registration page or contact us page we usually put different functions in order to validate the input from the user and based on that action is taken. [2]

Now putting this example is design pattern language; first we select a context where corresponding form validation is going to take place and then we apply a data checking strategy to establish pragmatically how different type of entries from users will be verified. This is indeed how strategy design pattern is implemented. [2]

In strategy pattern there is a predefined context that decides what course of action should be taken in accordance with the requirement of a specific strategy. [2]

There are several advantages of using strategy pattern [3];
  • If there is an object that is required to perform several behaviors, by using strategy pattern it becomes much simpler to keep track of each behaviour if it is dealt as a separate class. Adding more responsibilities to that class later on becomes much easier.
  • Changing behavior of object becomes easy as we just need to change the strategy followed by object.
  • Eliminates the need of having several conditional statements.
  • Number of classes are available and they differ only in their behaviour, then strategy pattern creates only one class and it uses different strategies, thus it results in easily manageable class.

References

[1] Strategy Design pattern
Available from URL
http://en.wikipedia.org/wiki/Strategy_pattern

[2] Alejandro Gervasio (2007) Introduction to Strategy Pattern
Available from URL
http://www.devshed.com/c/a/PHP/Introducing-the-Strategy-Pattern/

[3] Antonio Garcia, The Strategy Design pattern
Available from URL
http://www.exciton.cs.rice.edu/JAvaResources/DesignPatterns/StrategyPattern.htm

2 comments:

Bash said...

Well explained. The advantages are to the point as well, but at the same time there are some disadvantages as well. I can tell you one which is, it increases the number of objects in a class.

Abbas said...

cheers bash...