This blog is about patterns in real life, design pattern, software patterns, the Gang of Four patterns and anti-pattern relating to Software Development.

Monday, 30 April 2007

Strategy Pattern

[Blog 10]

The Strategy pattern is used to “define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.” [1]

Strategy pattern is used to reduce hard coding any algorithm into classes that will not always be used by them or the objects associated. Sometimes more than one algorithm might be needed, and if implemented in the class it will make maintenance of the program more complex. In order to prevent these problems, the strategy pattern creates classes that encapsulate those algorithms. Whenever an algorithm is need it is called or swapped with other functions to match the need of the interface.

Just think of an electric drill, it can be used to do a number of tasks just by changing the drill bits. For example, it can be used to make holes, screw, unscrew, hammer, and do wood work as well. The electric drill is the same at the end of the day, but its functions can be changed by swapping it with other functions.

The advantages of using strategy pattern are that the:

  • different algorithms can be grouped under a common class and called whenever needed.
  • New algorithms can be further added to expand the functionality of the interface
  • Possibility of switching to algorithms at run-time
  • The client can chose the algorithm needed without using a switch statement
  • Where sub classing is not an ideal option, strategy pattern can be used instead

The disadvantages of strategy pattern is that the:

  • The application must know all the strategies that are available
  • There will also be more objects [2]
I think Strategy pattern is a very useful pattern as it allows a pool of functions to be available and called whenever needed. There is no need for inheritance to occur to inherit functions. And also this allows expansion of the system very easily.

References:
[ref.1] - Design Patterns CD, Elements of Reusable Object-Oriented Software, by Erich Gamma et all, Addison Wesley Longman Inc.

[ref.2] - Design Patterns CD, Elements of Reusable Object-Oriented Software, by Erich Gamma et all, Addison Wesley Longman Inc.

1 Comments:

Blogger Gayan lakshitha said...

Hi (Gayan 372858)
Actually your explanation about strategy pattern very clear and understandable to every one.It has a good structure.
If you can add some participant and their responsibility this would be more understandable.

12 May 2007 at 09:36

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home