Skip to content
IT glossary
ProgrammingUpdated December 3, 2026

Strategy pattern

Стратегия

A behavioral design pattern that lets code swap between different ways of doing the same job without changing the code that calls them.

What the Strategy pattern changes

An online store follows the same checkout flow whether an order ships by courier or is collected in person. The delivery fee is the part that varies: the courier fee may depend on parcel weight, while pickup is free. With Strategy, each fee calculation lives separately, and checkout calls the selected calculation the same way every time.

How it works

The context is the code that needs a job done. Rather than implementing each version itself, it delegates the job to a strategy. All strategies follow the same contract. For a delivery calculation, that might mean accepting a weight in grams and returning a fee in cents. Two functions with the same type signature are not interchangeable if one returns cents and the other returns dollars.

Typically, the caller picks a strategy based on configuration or request data and passes it to the context. A context can receive its strategy once at construction or take one per call. The pattern does not require a setter or any other way to replace the strategy on an existing object.

Example in Python

A function is enough when the behavior can be expressed as a single call. Here, order_total does not need to know how delivery fees are calculated or which options the store offers.

from collections.abc import Callable

FeePolicy = Callable[[int], int]

def courier(weight_g: int) -> int:
    kilos = (weight_g + 999) // 1_000
    return 500 + 100 * kilos

def pickup(weight_g: int) -> int:
    return 0

def order_total(subtotal: int, weight_g: int, fee: FeePolicy) -> int:
    return subtotal + fee(weight_g)

policies = {"courier": courier, "pickup": pickup}
print(order_total(4_000, 1_200, policies["courier"]))  # 4700 cents

Adding locker delivery means writing a new fee function and registering it in policies. The lookup changes, but the code that totals the order does not.

When it helps

Use Strategy when the varying behavior has enough logic to test or change on its own. For example, teams can test each pricing policy against its own boundary cases, then pass a fixed-fee function to checkout to test how the fee contributes to the total. If the alternatives are two short, stable branches, a plain conditional may be easier to read. Strategy does not eliminate decisions; it separates choosing a behavior from carrying it out.

In interviews

A common prompt is to refactor a method whose switch mixes selection with several substantial algorithms. Point out what stays in the context, what moves into each strategy, and where selection happens afterward. If asked how Strategy differs from Factory, focus on intent: a factory creates an object, potentially a strategy; the strategy determines how an operation is performed.