Codacoda
Back to Academy

design patterns

Strategy

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from the clients that use it. The key participants are the Strategy (declares an interface common to all supported algorithms), ConcreteStrategy (implements the algorithm using the Strategy interface), and Context (is configured with a ConcreteStrategy object and maintains a reference to a Strategy object). Think of choosing a route on a map app: walking, driving, and cycling are different strategies for the same goal (getting from A to B), and you can switch between them at any time. Use Strategy when you have many related classes that differ only in their behavior, when you need different variants of an algorithm, or when a class defines many behaviors using conditional statements.

Use Cases

  • Sorting with different comparison strategies
  • Payment processing (credit card, PayPal, crypto)
  • Compression with different algorithms (zip, gzip, brotli)
  • Validation rules that vary by context

Visualization

strategyContext-strategy+executeStrategy()<<interface>>Strategy+algorithm()ConcreteStrategyA+algorithm()ConcreteStrategyB+algorithm()
Speed:1x
Strategy — defines a family of algorithms and makes them interchangeableStep 1 / 7

Implementation

Output

Click "Run Code" to see output...