Pattern: Strategy

Synopsis

The Strategy pattern is used to encapsulate a family of algorithms, making them interchangeable, so each algorithm can vary independently from client to client.

Context

Suppose you have related classes which differ only in their behavior. The Strategy pattern provides a way to configure a class with one of many behaviors. An example of this would be a system which has several algorithms for sorting an array such as Bubblesort, Insertionsort, and Quicksort. Furthermore, the class wants to decide at run-time which algorithm it should use to sort an array.

Forces

Solution

  1. Create an interface class (Strategy) which defines the interface to be used by the algorithms.
  2. Create the algorithm classes (ConcreteStrategy) which implement the Strategy interface.
  3. Have the class which uses the algorithms (Context) have a reference to the Strategy class.
  4. Configure the Context to choose the proper algorithm (ConcreteStrategy).

    The general Strategy pattern is as follows:

Consequences

Implementation

A link to example code can be found here: StrategyExample.zip

Related Patterns

State Pattern


References:
The Object Oriented Pattern Digest - http://patterndigest.com/patterns/Strategy.html
Strategy Pattern and J2EE by Raghvendra Singh - http://www.theserverside.com/patterns/thread.tss?thread_id=4777

Modified: 19-Apr-2004
Dustin Marceau