← Back to PatternPip

STRATEGY / THE IDEA IN A MINUTE

Same job.
A different way to do it.

Strategy lets you swap how a job is done while the code requesting it stays the same.

Give each approach the same contract: what it accepts, what it returns, and what it promises. The object using it—the context—asks for the work through that contract.

What varies?
The algorithm used to do a job.
What stays stable?
The context that requests the work, and the contract it relies on.
Where is the choice made?
In the caller or configuration, outside the context.

WATCH THE HANDOFF

Change the strategy. Keep the Sorter.

Try it yourself

Choose an approach, then send the same sorting request. Only the selected strategy does the work.

1. Choose a strategy

This choice belongs to the caller.
Sorter only knows the contract.

THE CALLER

Sort this list

THE CONTEXT

Sorter

Same object. Same code.strategy.sort(input)

“I ask my current strategy.
It decides how to sort.”

Bubble Sort

Selected

Compare neighbors. Swap those out of order.

sort(input)

Quick Sort

Waiting

Partition around a pivot. Sort each side.

sort(input)

BACK TO THE CALLER

Same promise. Different approach.

Ascending values. Original list preserved.

The result appears here after the handoff.

Bubble Sort is installed. Ask the Sorter to sort the list.

Try this: run Bubble Sort, switch to Quick Sort and run again. The active connection changes; the Sorter and its request stay the same.

Reduced motion is on; results appear immediately.

Useful when behavior keeps changing.

Several approaches do the same job, and you want to add or replace one without repeatedly editing the context.

Keep the cost in mind.

Extra interfaces and classes add structure to maintain. One function or a small, stable conditional may be enough. Strategy organizes change; it does not make an algorithm faster.

Choose your next step.