Strategy Pattern
Overview
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy
lets the algorithm vary independently from clients that use it.
Participants
- declares an interface common to all supported algorithms. Context uses this interface to
call the algorithm defined by a ConcreteStrategy.
- implements the algorithm using the Strategy interface.
- is configured with a ConcreteStrategy object.
- maintains a reference to a Strategy object.
- may define an interface that lets Strategy access its data.
Parameters
- name of the request operation to be created in the Context class.
- name of the method to be created for the entry point to a Strategy.
- how should the Context object be initialized:
- Constructor - Should it be initialized at creation time by passing in the Strategy to be
used, or
- Method - Should there be a set method so that the same Context could easily
use different Strategies by passing it the Strategy to be used before doing a request.
-
when selected, will create special JavaDoc links in the code between pattern participants, describing
their relationships.
Applicability
Use the Strategy pattern when
- many related classes differ only in their behavior. Strategies provide a way to
configure a class with one of many behaviors.
- you need different variants of an algorithm. For instance, you might define
algorithms reflecting different space/time trade-offs. Strategies can be used
when these variants are implemented as a class hierarchy of algorithms.
- an algorithm uses data that clients shouldn't know about. Use the Strategy pattern to
avoid exposing complex, algorithm-specific data structures.
- a class defines many behaviors, and these appear as multiple conditional statements
in its operations. Instead of many conditionals, move related conditional
branches into their own Strategy class.