Strategy

Encapsulating interchangeable algorithms behind a common interface — replacing conditionals, choosing strategies at runtime, strategies as functions, and real-world uses like comparators and pricing rules.

Beginner 2 min readLesson 14 of 24 Interview Q&A

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

It's the most-used behavioural pattern, and the clearest example of "favour composition over inheritance": the context has a strategy instead of being one.

Checkout (context)pricing: PricingStrategy«interface» PricingStrategyprice(cart)RegularBlackFridayMember

From conditionals to strategies

Before: a growing switch
Java
double price(Cart cart, String mode) {
    if (mode.equals("regular")) {
        return cart.subtotal();
    } else if (mode.equals("blackfriday")) {
        return cart.subtotal() * 0.7;
    } else if (mode.equals("member")) {
        return cart.subtotal() * 0.9
             - (cart.items() > 5 ? 10 : 0);
    }
    throw new IllegalArgumentException();
}

Every new promotion edits (and risks breaking) this method.

After: strategies
Java
interface PricingStrategy {
    double price(Cart cart);
}

class Regular implements PricingStrategy {
    public double price(Cart c) {
        return c.subtotal();
    }
}
class BlackFriday implements PricingStrategy {
    public double price(Cart c) {
        return c.subtotal() * 0.7;
    }
}

Each algorithm is separate, testable, and new ones don't touch existing code.

Full example

interface PricingStrategy { double price(Cart cart); }

class Regular implements PricingStrategy {
    public double price(Cart c) { return c.subtotal(); }
}
class PercentOff implements PricingStrategy {
    private final double pct;
    PercentOff(double pct) { this.pct = pct; }
    public double price(Cart c) { return c.subtotal() * (1 - pct / 100); }
}
class BuyXGetOneFree implements PricingStrategy {
    private final int x;
    BuyXGetOneFree(int x) { this.x = x; }
    public double price(Cart c) {
        int free = c.items() / (x + 1);
        return c.subtotal() - free * c.cheapestItemPrice();
    }
}

class Checkout {
    private PricingStrategy pricing;
    Checkout(PricingStrategy pricing) { this.pricing = pricing; }
    void setPricing(PricingStrategy p) { this.pricing = p; }       // swap at runtime
    double total(Cart cart) { return pricing.price(cart) + shipping(cart); }
}

// Strategies are often just lambdas: PricingStrategy is a functional interface
Checkout checkout = new Checkout(c -> c.subtotal() * 0.8);

Strategies everywhere

WhereStrategy
SortingComparator / key= function passed to sort
CompressionDeflater levels, gzip vs brotli vs zstd
AuthPassport.js strategies (local, Google, GitHub)
RetriesBackoff policy objects (fixed, exponential, jittered)
Load balancingRound robin, least connections, consistent hash
CachingEviction policy (LRU, LFU, FIFO)
ValidationPluggable validators per field
Routing / mapsShortest vs fastest vs no-tolls path

Choosing the strategy

Something must pick the strategy: configuration, a factory/registry keyed by name, user choice, or rules (feature flags, A/B tests). Keep that selection logic in one place, separate from the algorithms.

When to use this pattern
  • Several variants of an algorithm, selected at runtime.
  • A method with a growing if/else or switch on a "mode" or "type".
  • You want to test each algorithm in isolation.
  • Not worth it for two trivial branches that will never grow.
Key takeaways
  • Strategy encapsulates interchangeable algorithms behind one interface.
  • It replaces conditionals with polymorphism (open/closed principle).
  • In modern languages, a strategy is often just a function or lambda.
  • Keep strategy selection (factory, config) separate from the strategies.
Interview questions
QStrategy vs State: what's the difference?medium

Both delegate to an interchangeable object. In Strategy, the client chooses the algorithm and strategies are independent and unaware of each other. In State, the object's behaviour changes as its internal state changes, and state objects typically trigger transitions to other states themselves.