Oct 1, 2013

Strategy pattern in a nutshell

The strategy pattern is a behavioural pattern. According to Wikipedia is  also known as the policy pattern (not sure by whom, but Wikipedia holds a lot of untold truths)

The book definition reads:

Defines a set of encapsulated algorithms that can be swapped to carry out a specific behaviour
 
To be able to use this pattern properly, take a minute to think about this three things:
  1. Isolate the behaviors you need and define an interface that applies to all of them.
  2. Implement the different behaviors. Each behavior IMPLEMENTS the interface.
  3. The main object HAS-A behavior interface container from which the selected behavior will be called.

Diagram:

Strategy Pattern Diagram

Where Would I Use This Pattern?

The Strategy pattern is to be used where you want to choose from algorithms used at runtime
 
Some examples where you may find this pattern:
  • Save to different formats
  • Payment methods
  • Sorting algorithms
  • File compression

 

References:

http://en.wikipedia.org/wiki/Strategy_pattern

No comments:

Post a Comment