← Home
🏗Crack System Design with DSA AnimatorSystem DesignNEW
🏗 System Design›Behavioral Patterns

🎯Strategy Pattern

Define a family of algorithms, encapsulate each one, and make them interchangeable.

📌 Key IdeaPull varying behaviour behind `Strategy` interface; Context delegates without switch. Same structural idea as State — intent differs: Strategy plugs policies chosen externally.
🖼

Visual

🎯 Inject policy at runtime
  PriceCalculator ctx =
      new PriceCalculator(new HolidayDiscountStrategy());

  ctx.quote(cart);  // swap strategy → new behaviour

Open/Closed — add new pricing strategy without editing checkout core.

✅

When to Use

  • Multiple ways to accomplish same task (sorting, pricing, routing rules).
  • You want to swap behaviour per customer segment / config / feature flag.
  • Eliminate growing if/switch on type codes.
🚫

When NOT to Use

  • Only one algorithm ever — inline it.
  • You're modelling lifecycle phases — often State fits better.
🚨

Anti-Pattern (What NOT to Do)

Switch on payment typeBadjava
Money fee(PaymentType t) {
    return switch (t) {
        case CARD -> ... case UPI -> ...
    };
Every new payment method edits this method.
✅

The Right Way

Strategy per typeGoodjava
interface FeeStrategy { Money compute(Order o); }

class Checkout {
    private final FeeStrategy fees;
    Money total(Order o) { return fees.compute(o); }
}
Wire fees via DI — new strategy = new class.
⚖️

Pros & Cons

👍 Pros
  • Eliminates conditional spaghetti.
  • Strategies unit-test in isolation.
  • Runtime selection — configuration-driven behaviour.
👎 Cons
  • Many small interfaces — discoverability matters.
  • Clients must pick sensible default strategy.
🔀

Common Confusions Cleared Up

Strategy vs Template Method

Template Method fixes skeleton in base class, subclasses override hooks. Strategy composes whole algorithm via object injection — no inheritance needed.

🎤

Interview Q&A

🔮

Likely Follow-up Questions

  • Policy pattern (Martin Fowler) — same as Strategy?
🧾

Quick Cheat Sheet

IntentPluggable interchangeable algorithms.
vs StatePolicy vs lifecycle object.
vs Template MethodComposition vs inheritance skeleton.
🔗

Related Topics