Skip to main content
Design Patterns 80 XP · 8 min

Strategy: Algorithm Swapping

Define a family of algorithms, encapsulate each in its own class, and make them interchangeable at runtime — eliminate conditionals by selecting behavior through composition.

Showing
Ad (728×90)

Why this matters

A checkout that handles PayPal, card, and bank transfer with a long if/elif block violates the Open-Closed Principle: adding crypto requires editing the checkout class. Strategy encapsulates each algorithm in its own class and injects it at the call site. The checkout delegates to whatever strategy it receives — adding crypto means writing a new class and wiring it in, zero edits to existing code.

The problem

Bad

The solution

Good

Strategy vs. State

Strategy and State look structurally identical — both inject a polymorphic object that the context delegates to. The difference is intent: a Strategy is selected by the client and usually doesn't change after construction; a State transitions itself internally as the object moves through its lifecycle. When in doubt: if the algorithm is chosen externally, it's a Strategy; if the object changes its own behavior over time, it's a State.

Key takeaway

Every if/elif on a "type" field that selects an algorithm is a Strategy waiting to be extracted — encapsulate each variant, inject it, and new variants add code rather than modifying it.

Done with this lesson?

Mark it complete to earn XP and track your progress.