architecture

PatternExplorer

Behavioral Pattern

Strategy Pattern

Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

lightbulb Analogy

Imagine a navigator app. Whether you choose "Walk", "Drive", or "Public Transit", the destination remains the same, but the route calculation strategy changes. The app context delegates the work to the selected strategy.

Strategy Pattern Illustration

play_circle Interactive Demo: Payment Processor

CONTEXT: PaymentContext
credit_card

Paying with Credit Card

Processing standard transaction...

Final Charge $100.00

thumb_up Advantages

  • check_circle Open/Closed Principle: You can introduce new strategies without changing the code of the context.
  • check_circle Runtime Switching: Unlike inheritance, strategies can be swapped at runtime (as seen in the demo).
  • check_circle Isolation: Implementation details of an algorithm are isolated from the code that uses it.

thumb_down Disadvantages

  • cancel Complexity: If you only have a few algorithms that rarely change, the pattern adds unnecessary classes.
  • cancel Client Awareness: The client must be aware of the differences between strategies to select the right one.