GofPatterns GofPatterns

Behavioral Patterns  «Prev  Next»

Strategy Pattern

The intent of the Strategy Pattern is to define a family of algorithms, encapsulate each algorithm, and make them interchangeable. The Strategy Pattern lets the algorithm vary independently from clients that use it. In addition the pattern, defines a group of classes that represent a set of possible behaviors. These behaviors can then be used in an application to change its functionality.
The figure below illustrates the Strategy pattern.

StrategyContext aggregates abstract Strategy class. Three concrete class implementations inherit from abstract Strategy.

Strategy Pattern Code


The following lists the benefits of using the Strategy pattern:
  1. An alternative to subclassing
  2. Defines each behavior in its own class, which eliminates conditional statements
  3. Easier to extend a model to incorporate new behaviors without recoding the application

When to Use:

You should use the Strategy pattern when:
  1. Many related classes differ only in their behavior.
  2. You need different variants of an algorithm.
  3. An algorithm uses data unknown to clients.