The Strategy pattern is used to encapsulate a family of algorithms, making them interchangeable, so each algorithm can vary independently from client to client.
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.
- You need different variants of an algorithm.
- Algorithms use data that the client shouldn't know about.
- A class has many behaviors which appear as a multiple condition statement.
- Create an interface class (Strategy) which defines the interface to be used by the algorithms.
- Create the algorithm classes (ConcreteStrategy) which implement the Strategy interface.
- Have the class which uses the algorithms (Context) have a reference to the Strategy class.
- Configure the Context to choose the proper algorithm (ConcreteStrategy).
The general Strategy pattern is as follows:
![]()
- Eliminates large conditional statements.
- Provides a choice of implemenation for same behavior.
- Allows for easy addition of more implementations.
- Increases number of classes and objects.
- Binds implementations to a specific interface.
State Pattern
Modified:
19-Apr-2004
Dustin Marceau