Strategy Pattern
(from Design
Patterns)
Synopsis
Define a family of algorithms, encapsulate each one, and make them
interchangeable. Strategy lets the algorithms vary independently from
clients that use it. A Decorator lets you
change the skin of an object; a Strategy lets you change the guts.
Context
The algorithm that a object uses is highly variable and can be reused
elsewhere.
Forces
-
Different algorithms may be applicable at different times.
-
The same algorithm may be applicable in different objects.
-
The algorithm may use data that the object doesn't need to know about.
Solution
Encapsulate the different algorithms by defining objects for them (strategy
objects). Objects which use the algorithm hold a reference to the strategy
object. Switch algorithms by switching strategy objects.
Consequences
-
Families of strategy objects can cover the range of tradeoffs like time
vs. space.
-
The strategy object can encapsulate algorithm-specific data structures.
-
The different strategy objects can use inheritance to reuse common code.
-
An object can switch strategies at run-time, e.g. to tune itself to the
current workload or to reflect different states. A "disabled" state might
be implemented by a strategy object that does nothing. This eliminates
conditional statements in the object.
Implementation
-
If there is no need to change a strategy at run-time, you can use a C++
template to configure an object with a strategy.
See Design
Patterns for sample code.
Known Uses
-
ET++ uses the Strategy pattern to encapsulate layout algorithms for text
viewers.
-
Drawing programs like UniDraw use the Strategy pattern to select different
tools. This makes it easy to add new tools.
-
MacApp uses the Strategy pattern, rather
than the Decorator pattern, to add adornments
and event handlers to a window.
-
Borland's ObjectWindows uses strategies to encapsulate validation
algorithms for dialog box entry fields. For example, a numeric field
might have a validator to check proper range, a string field might have a
validator for proper syntax, etc.
-
Strategy objects have also been used for sorting algorithms, memory allocation
algorithms, graph layout algorithms, and register allocation schemes.
Thomas Minka
Last modified: Sat Jan 11 17:56:02 EST 1997