Skip to main content

What It Is

The Strategy pattern makes an algorithm swappable: the surrounding code stays the same, and the interchangeable part — how to price, how to sort, how to compress — is plugged in as a value.

TypeScript can write a strategy two ways: as a class implementing an interface, or as a plain function type. This page uses the function type, because the strategy here is one calculation with no state of its own — type Pricing = (price: number) => number and an assignment are the whole mechanism.


Example: Swappable Pricing

Shop never changes; the pricing rule is a function value in a field. Regular price, Black Friday, member discount — three functions, one shop.

The strategy is a function value

Three checkouts of the same 50 give three totals — 50.00, 35.00 and 45.00 — and only the assigned function differs. This is also how sorting works: array.sort(compare) takes the comparison strategy.

Prompt
Write a TypeScript program with the Strategy pattern using a function type: a Pricing type taking and returning a number, three strategies (regular, Black Friday at 30% off, member minus 5), and a Shop class holding the current pricing function used by its checkout method, which prints the total with two decimals. Check out the same price with all three strategies.
Output: TypeScript file and captured output

When to Use It

Use it whenever an algorithm varies while its surroundings do not: pricing rules, retry policies, sorting orders, validation modes.

Skip it when there is one algorithm and no realistic second. Use the interface-and-class form instead of a function only when a strategy needs its own state or several methods.


Pros and Cons

Pros: behavior swaps at run time; each strategy is small and testable alone; as a function type it is nearly free — one type alias and an assignment.

Cons: the chosen strategy is invisible at the call site — debugging means finding what was assigned; too many micro-strategies fragment simple logic.