Course contentsShow
← Software Engineering
Lesson 205 of 1,9336. SOLID PrinciplesFree lesson

The Strategy Pattern and OCP

See how the Strategy pattern exemplifies OCP by allowing behavior changes through composition.

The Strategy Pattern and OCP

What you'll learn: How the Strategy pattern lets you add new behaviors without modifying existing code, perfectly demonstrating the Open/Closed Principle.

The Core Idea

The Strategy pattern is a design pattern that encapsulates different algorithms or behaviors into separate classes, all implementing the same interface. Instead of hardcoding behavior into a class, you inject the behavior from outside. This is a textbook example of the Open/Closed Principle in action.

Think of it like a navigation app: the app itself doesn't need to change when you want to switch from "fastest route" to "scenic route" to "avoid tolls." Each routing strategy is separate, and you just swap them in.

How Strategy Exemplifies OCP

When you use the Strategy pattern:

  • Closed for modification: Your main class doesn't change when you add new strategies. It depends on an interface, not concrete implementations.
  • Open for extension: You create new strategy classes implementing the interface whenever you need different behavior.

Example scenario: Imagine a payment processor that handles credit cards, PayPal, and cryptocurrency. Without Strategy, you'd have a giant if-else block that grows every time you add a payment method (violating OCP). With Strategy, you define a PaymentStrategy interface and create separate classes for each method. Adding Bitcoin payment? Just create a new BitcoinPaymentStrategy class—no modifications to existing code.

The Power of Composition

The Strategy pattern uses composition (your class has-a strategy) rather than inheritance. This gives you runtime flexibility—you can swap strategies on the fly based on user choice or context, without changing the code that uses them.

Key Takeaway: The Strategy pattern demonstrates OCP by letting you extend behavior through new strategy classes while keeping existing code untouched. It's composition-based extensibility at its finest.