Skip to content
BENIBIX Learn

Strategy Pattern

Development🏗️ ArchitectureDesign Patterns

Also known as Strategy, Policy Pattern

Pick how a job is done while the program runs.

Think of it like

Think of it like picking how to get to school. Bike, bus or walk, you still end up at school.

Example

Emma's shop works out shipping three ways: standard, express and pickup. Checkout is handed the one the buyer picked and calls it, with no long if-else chain.

Why it matters

It replaces long chains of if and else with small parts that are easy to test and add to.

Definition

The strategy pattern lets you swap one way of doing a job for another. It can happen while the program runs. Each way, or strategy, sits in its own small piece of code with the same shape. The main code is handed a strategy and simply calls it. To add a new way, you write a new strategy and leave the main code alone. In many languages, passing a function is the simplest form of it.

Common mistake

Building classes for two choices that never change. A simple if is clearer until there are more.

Key takeaways

  1. 1
    Same shape. Many ways to do it.
  2. 2
    Swap at run time. Pick the one you need.
  3. 3
    Add without editing. Main code stays put.