Skip to content
Behavioral

Strategy

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

Intent

Enable an object to select a behavior at runtime by encapsulating each algorithm behind a common interface and delegating execution to the currently assigned strategy object.

Problem

You have a class that needs to perform a task in several different ways, and you find yourself using large conditional blocks (if/else or switch) to pick the right variation. Adding a new variation requires modifying existing code, violating the Open-Closed Principle and making the class harder to test and maintain.

Solution

Extract each algorithm into its own class that implements a common Strategy interface. The original class (Context) holds a reference to a Strategy and delegates the work to it. Clients can swap strategies at runtime by injecting a different implementation, keeping the Context class thin and closed for modification.

Participants

  • Strategy — declares an interface common to all supported algorithms
  • ConcreteStrategy — implements the algorithm using the Strategy interface
  • Context — maintains a reference to a Strategy object and delegates algorithmic work to it

Advantages

  • Eliminates conditional statements for selecting behavior
  • Each algorithm is isolated in its own class, making it easy to test, extend, and swap
  • Follows the Open-Closed Principle — new strategies can be added without changing the Context
  • Strategies can be shared across different contexts if they are stateless

Disadvantages

  • Clients must be aware of the different strategies and understand when to choose each one
  • Increases the number of classes in the system, which can feel like over-engineering for simple cases
  • Communication overhead between Context and Strategy if the interface is too broad or too narrow

Real-World Analogy

Consider different routes to the airport. You can drive, take a bus, cycle, or call a cab. Each is a different strategy for solving the same problem — getting to the airport. The choice depends on budget, time, and comfort, but the destination remains the same. You can switch your transportation strategy right up until you leave the house.

Use Cases

  • Sorting algorithms — swap between quicksort, mergesort, or heapsort depending on data characteristics
  • Payment processing — select between credit card, PayPal, bank transfer, or crypto at checkout
  • Compression — choose between gzip, brotli, or zstd for different performance/size trade-offs
  • Validation rules — apply different validation strategies depending on user role or form type
  • Pricing engines — apply seasonal, VIP, or coupon-based discount strategies

Code Examples

A Compressor context delegates to interchangeable CompressionStrategy objects. New algorithms can be added without modifying the Compressor class.