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.
Choose an approach, then send the same sorting request. Only the selected strategy does the work.
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.”
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.
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.
Learn through an example
Follow three short chapters: one sorting job, a changing requirement, then a replaceable strategy.
Live sorting tool · optional practiceBACK FOR A REFRESHERQuick reference
Scan the roles, a compact code example, and the mistakes to avoid. Open it directly whenever you need it.
TypeScript / Kotlin · bookmarkable