Behavioral PatternsStrategy PatternEasy⏱️ ~2 min

Strategy Pattern - Definition and Core Problem

Definition
Strategy Pattern is a behavioral design pattern that defines a family of algorithms, encapsulates each one in a separate class, and makes them interchangeable at runtime.

What Problem Does It Solve?

When you have multiple ways to perform an operation and need to switch between them dynamically, hardcoding all variations in a single class leads to bloated, rigid code that violates the Open/Closed Principle (OCP). The Strategy Pattern eliminates conditional logic for algorithm selection by delegating behavior to pluggable strategy objects.

Without Strategy Pattern

Consider a payment processing system. A naive implementation would use conditional statements:

class PaymentProcessor:
  method processPayment(amount, type):
    if type == "CREDIT_CARD":
      // credit card logic
    else if type == "PAYPAL":
      // PayPal logic
    else if type == "CRYPTO":
      // cryptocurrency logic

Problems: First, every new payment method requires modifying existing code (violates OCP). Second, the class grows exponentially with each variant. Third, testing becomes complex as all branches must be covered. Fourth, different teams cannot work independently on payment methods.

With Strategy Pattern

Each payment method becomes a separate strategy class implementing a common interface. The context switches strategies at runtime without knowing implementation details.

Interview Tip: Always explain Strategy Pattern solves the "many ways to do one thing" problem. Differentiate it from State Pattern (which handles "one thing that behaves differently based on internal state").
💡 Key Takeaways
Encapsulates algorithms into separate strategy classes with a common interface
Enables runtime algorithm selection without conditional logic
Adheres to Open/Closed Principle by allowing new strategies without modifying existing code
Context delegates behavior to strategy object instead of implementing all variants
Each strategy is independently testable and maintainable
📌 Examples
1Payment processing with multiple payment methods (credit card, PayPal, cryptocurrency)
2Pricing calculators with different discount strategies (seasonal, bulk, loyalty)
3Compression algorithms (ZIP, RAR, GZIP) selectable at file save time
← Back to Strategy Pattern Overview
Strategy Pattern - Definition and Core Problem | Strategy Pattern - System Overflow