Enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.
Deferring the decision about which algorithm to use until runtime allows the calling code to be more flexible and reusable.
For instance,
a class that performs validation on incoming data may use the strategy pattern to select a validation algorithm depending on the type of data, the source of the data, user choice, or other discriminating factors.
These factors are not known until run-time and may require radically different validation to be performed.
The validation algorithms (strategies), encapsulated separately from the validating object, may be used by other validating objects in different areas of the system (or even different systems) without code duplication.
The strategy pattern stores a reference to some code in a data structure and retrieves it with function pointer, the first-class function, classes or class instances.
In the strategy pattern, behaviors are defined as separate interfaces and specific classes implement these interfaces.
This allows better decoupling between the behavior and the class that uses the behavior. The behavior can be changed without breaking the classes that use it, and the classes can switch between behaviors by changing the specific implementation used without requiring any significant code changes. Behaviors can also be changed at run-time as well as at design-time.
UML Class & Sequence diagrams
In the above UML class diagram,
The Context classdoesn't implement an algorithm directly.
Instead, Context refers to the Strategy interface for performing an algorithm (strategy.algorithm()), which makes Context independent of how an algorithm is implemented.
The Strategy1 and Strategy2 classes implement the Strategy interface, that is, implement (encapsulate) an algorithm.
The UML sequence diagram shows the run-time interactions:
The Context objectdelegates an algorithm to different Strategy objects.
First, Context calls algorithm() on a Strategy1 object, which performs the algorithm and returns the result to Context.
Thereafter, Context changes its strategy and calls algorithm() on a Strategy2 object, which performs the algorithm and returns the result to Context.