Strategy

Strategy

Intent

Define a family of algorithms, encapsulate each one, and make them interchangable. Strategy lets the algorithm vary independently from clients that use it.

Also known as

Policy

Applicability

Use the Strategy pattern when:

  • Many related classes differ only in their behaviour. Strategies provide a way to configure a class with one of many behaviors.
  • You need different variants of an algorithm.
  • An algorithm use data that clients shouldn't know about.
  • A class defines many behaviors, and these appear as multiple conditional statements in it's operations.

Structure

Orange

Participants

  • Strategy: declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy.
  • ConcreteStrategy: implements the algorithm using the Strategy interface.
  • Context: is configured with a ConcreteStrategy object, maintains a reference to Strategy object, may define an interface that lets Strategy access it's data.

Collaborations

  • Strategy and Context interact to implement the choose algorithm.
  • A context forwards requests from it's clients to it's strategy.

Consequences

The Strategy pattern has the following benefits and drawbacks:

  • Hierarchies of Strategy classes define a family of algorithms or behaviors for contexts to reuse.
  • An alternative to subclassing.
  • Strategies eliminate conditional statements.
  • Clients must be aware of different strategies.

Sample Code

Strategy

Related Patterns

Strategy objects often make good flyweights.