Course contentsShow
← Software Engineering
Lesson 312 of 1,9339. Behavioral Design PatternsFree lesson

Strategy Pattern: Encapsulating Algorithms

Define a family of interchangeable algorithms and select one at runtime to vary behavior independently from clients.

Strategy Pattern: Encapsulating Algorithms

What you'll learn: How to swap out algorithms at runtime without changing the code that uses them.

The Core Idea

The Strategy Pattern lets you define a family of interchangeable algorithms, encapsulate each one in its own class, and make them swappable at runtime. The client code doesn't need to know which specific algorithm is being used—it just calls a common interface.

Think of it like choosing a payment method at checkout: whether you select credit card, PayPal, or cash, the store processes your payment the same way. The payment strategy varies, but the checkout process remains unchanged.

Why Encapsulate Algorithms?

Without the Strategy Pattern, you might have conditional logic scattered throughout your code:

if (useAlgorithmA) {
    // do A
} else if (useAlgorithmB) {
    // do B
}

This violates the Open/Closed Principle—adding a new algorithm means modifying existing code. Strategy Pattern fixes this by pulling each algorithm into its own class that implements a shared interface.

Structure

You have three key parts:

  1. Strategy interface – defines the method signature all algorithms must implement
  2. Concrete strategies – each class implements one specific algorithm
  3. Context – holds a reference to a strategy and delegates work to it

The context can switch strategies at runtime without knowing implementation details, similar to how the State Pattern switches state objects, but Strategy focuses on varying behavior rather than state-dependent behavior.

When to Use It

  • When you have multiple ways to perform an operation (sorting, compression, routing)
  • When you want to avoid long conditional chains
  • When algorithms should be selected or swapped at runtime

Key Takeaway: The Strategy Pattern encapsulates a family of algorithms behind a common interface, allowing you to select and swap implementations independently from the code that uses them.