Strategy

behavioral

Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Intent

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Motivation

When you have multiple algorithms for a specific task and want the client to choose which algorithm to use at runtime, the Strategy pattern is useful. It's an alternative to conditional statements.

Structure

The pattern involves a Strategy interface that defines an algorithm. ConcreteStrategy classes implement different versions of the algorithm. A Context class uses a Strategy.

Participants

  • •Strategy - declares an interface common to all supported algorithms
  • •ConcreteStrategy - implements the algorithm using the Strategy interface
  • •Context - is configured with a ConcreteStrategy object and maintains a reference to a Strategy object

Pros

  • ✓Families of related algorithms
  • ✓Alternative to subclassing
  • ✓Eliminates conditional statements
  • ✓Provides different implementations of the same behavior

Cons

  • ✗Clients must be aware of different strategies
  • ✗Communication overhead between Strategy and Context
  • ✗Increased number of objects

Use Cases

Different sorting algorithms
Payment methods
Compression algorithms
Route planning strategies
Validation rules

Implementation Tips

Considerations

  • •Define Strategy and Context interfaces carefully
  • •Consider whether strategies need data from Context
  • •Think about strategy selection mechanism

Tips

  • •Use dependency injection for strategies
  • •Consider using function objects for simple strategies
  • •Make strategies stateless when possible
  • •Document when to use which strategy

Interactive Code Editor

Related Patterns