Strategy Pattern

Also Known As: Policy

The Strategy pattern is useful when there is a set of related algorithms (as opposed to states in state pattern) and a client object needs to be able to dynamically pick and choose an algorithm from this set (or hierarchy) that suits its current need. The Strategy pattern suggests keeping the implementation of each of the algorithms (such as encryption or logging) in a separate class. Each such algorithm encapsulated in a separate class is referred to as a strategy. An object that uses a Strategy object is often referred to as a context object. With different Strategy objects in place (all implementing one common interface), changing the behavior of a Context object is simply a matter of changing its Strategy object to the one that implements the required algorithm.

Structure

Similar to state pattern

Collaborations

  • A context may pass all data required by the algorithm to the strategy when the algorithm is called. Alternatively, the context can pass itself as an argument to Strategy operations. That lets the strategy call back on the context as required.
  • A context forwards requests from its clients to its strategy. Clients usually create and pass a ConcreteStrategy object to the context; thereafter, clients interact with the context exclusively. There is often a family of ConcreteStrategy classes for a client to choose from.

Consequences

  • Lots of conditional code indicates the need to have strategy pattern
  • Client should be aware of different strategies at hand

Related Patterns

  • Strategies can be share using flyweight pattern
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License