Design Patterns

The Strategy Pattern Explained for Beginners

By CodeHeights Editorial Team · · 4 min read

Design patterns have an intimidating reputation, but most of them describe ideas you have probably already used without a name. The strategy pattern is one of the friendliest. It answers a common question: how do I let a program choose between several ways of doing the same job, without a tangle of conditions?

This article explains the pattern in plain language, builds a small example, and shows when it helps and when it is more machinery than you need.

The Problem It Solves

Imagine an online shop that must calculate shipping. There are a few methods: standard delivery, express delivery, and in-store pickup. Each one calculates the cost differently. A first attempt often looks like this.

def shipping_cost(method, weight):
    if method == "standard":
        return weight * 1.0
    elif method == "express":
        return weight * 2.5 + 5
    elif method == "pickup":
        return 0
    else:
        raise ValueError("Unknown method")

This works for three methods. But what happens when a fourth arrives, and a fifth? Every new option means editing this function, which risks breaking the ones that already work. The function also mixes two jobs: deciding which method applies and knowing how each one works. Over time, such conditions spread across the codebase.

The Idea in One Sentence

The strategy pattern puts each interchangeable behavior in its own piece, gives them all the same shape, and lets the calling code pick one to use.

The three parts are:

  • The strategy: a shared contract that says what any version of this behavior must be able to do.
  • Concrete strategies: the individual versions, each following the contract.
  • The context: the code that needs the behavior and uses whichever strategy it is given.

The context does not know or care which strategy it holds. It just calls the agreed-upon method.

Building It Step by Step

In Python, a strategy can be as simple as a function. Each shipping method becomes its own small function with the same signature.

def standard(weight):
    return weight * 1.0

def express(weight):
    return weight * 2.5 + 5

def pickup(weight):
    return 0

Now the context takes a strategy as an argument.

class Order:
    def __init__(self, weight, shipping_strategy):
        self.weight = weight
        self.shipping_strategy = shipping_strategy

    def shipping_cost(self):
        return self.shipping_strategy(self.weight)

order = Order(4, express)
print(order.shipping_cost())

The Order class has no if statements about shipping methods. To add a new method, you write one new function and pass it in. The existing code stays untouched.

In languages that lean on classes, you would define an interface with a single method, then write one class per strategy. The idea is identical. Only the packaging differs.

Swapping Behavior at Runtime

Because the strategy is just a value, you can change it while the program runs. A user selecting "express" at checkout can simply cause your code to look up the matching function.

strategies = {
    "standard": standard,
    "express": express,
    "pickup": pickup,
}

chosen = strategies["express"]
order = Order(4, chosen)

This dictionary lookup replaces the long chain of conditions. The choice happens in one place, and the rest of the program works with whatever strategy it receives.

Where You Have Already Seen It

Strategy appears throughout everyday programming, often disguised.

  • Sorting with a custom comparison. When you pass a function that tells a sort routine how to order items, you are handing it a strategy.
  • Validation rules. Different forms may need different validators plugged into the same form handler.
  • Payment or export formats. The same screen can save data as different file types by swapping the writer.
  • Logging destinations. The same logging call can write to a file, the console, or a remote service depending on configuration.

Recognizing the pattern in existing tools makes it easier to apply in your own code.

When Not to Use It

Patterns are tools, not goals. Strategy adds a little structure, so it must earn its place.

If you have only two behaviors and they will never change, a simple condition is clearer. If the behaviors are tiny and used in a single location, extra pieces add noise. Reach for strategy when you see signs such as:

  1. A chain of conditions that grows every time a new variant appears.
  2. The same decision repeated in several parts of the code.
  3. A need to choose the behavior at runtime or from configuration.
  4. A wish to test each behavior in isolation.

The testing benefit is real. Each strategy is a small, independent function, so you can verify it with a handful of inputs without setting up the rest of the program.

A Quick Checklist

When designing your own strategy, ask yourself:

  • Do all variants take the same inputs and return the same kind of result?
  • Is the code that uses the behavior free of any knowledge about which variant it is running?
  • Can I add a new variant without changing existing ones?

If the answer to all three is yes, you have applied the pattern well.

Frequently Asked Questions

Is the strategy pattern the same as using if statements?

It has the same goal, which is choosing between behaviors, but it moves each behavior into its own unit. This keeps the calling code stable as new variants are added, whereas a long if chain must be edited each time.

Do I need classes to use it?

No. In languages that treat functions as values, such as Python and JavaScript, plain functions work well. Classes are useful when a strategy needs to hold its own data or settings.

How is it different from the state pattern?

They look similar in structure, but the purpose differs. Strategy lets the caller choose an algorithm, while state lets an object change its behavior as its own internal condition changes.

Related reading