OOP in Practice · Episode 8 of 70 · Design Patterns · Beginner · TypeScript 7.0.2
The problem
You’re building the checkout for an online shop that ships through three couriers. The strategy design pattern fits here because every courier prices a parcel its own way. StandardPost charges per started 500 g, ExpressAir per kilogram (bulky parcels by volume), and BoxFlat one flat fee if the parcel fits its box. Today it is all one switch, and rates change every quarter.
Your task: redesign the calculator so each courier’s rule is its own object, and the calculator can quote, compare and add couriers without being edited.
Requirements
- Quote one parcel with any registered courier, by name.
- Quote all couriers and return the cheapest available one.
- A courier that cannot take a parcel (too heavy, too big) says why, instead of returning a wrong price.
- Invalid parcels (zero or negative weight or size) and unknown courier names are rejected.
- A new quarter’s rates and a new courier need no change to the calculator class.
Constraints and assumptions
- Single process, in memory. Money is whole paise (1 rupee = 100 paise) to avoid float rounding.
- All rates, limits and the 5,000 cm³/kg volumetric divisor are practice numbers, not any real courier’s rate card.
- No npm packages; plain TypeScript compiled with
tsc --strict.
What this tests: strategy pattern, polymorphism, open/closed principle, interfaces, discriminated unions, input validation
The strategy design pattern puts each interchangeable algorithm in its own class behind one interface. Here ShippingStrategy declares quote(parcel); StandardPost, ExpressAir and BoxFlat each implement it. ShippingCalculator stores strategies by name and calls quote() without knowing the class, so new rates or couriers never touch it.
Try it yourself first — hint
Every case in the switch answers one question: “what does this courier charge for this parcel, if anything?” Make that question an interface method, and make each answer a class.
Step 1: Identify the objects and responsibilities
| Class / interface | Responsibility | Key methods |
|---|---|---|
Parcel |
Weight, size and zone. Rejects zero, negative or fractional values. | longestSide, volumeCm3 |
Quote (union type) |
Either a price with a detail line, or “unavailable” with a reason. | — (field ok) |
ShippingStrategy (interface) |
The one shape every courier rule must have. | courier, quote() |
StandardPost, ExpressAir, BoxFlat |
One courier’s pricing rule each. Rates come in through the constructor. | quote() |
ShippingCalculator (context) |
Registers strategies by name, rejects duplicates and unknown names, compares quotes. | register(), quote(), quoteAll(), cheapest() |
PickupPoint (demo) |
A courier added after the calculator was written. | quote() |
Step 2: The naive approach and why it breaks
type Parcel = { grams: number; l: number; w: number; h: number; zone: string };
function shippingCost(courier: string, p: Parcel): number {
switch (courier) {
case "StandardPost": {
const steps = Math.ceil(p.grams / 500);
return p.zone === "local" ? 40 + steps * 12 : 60 + steps * 20;
}
case "ExpressAir": {
const kg = Math.ceil(Math.max(p.grams, (p.l * p.w * p.h) / 5) / 1000);
return kg * (p.zone === "local" ? 55 : 90);
}
case "BoxFlat":
return 99; // "flat box" -- but nobody checks the box size
default:
return 0; // unknown courier... ships free?
}
}
const book: Parcel = { grams: 1200, l: 30, w: 20, h: 10, zone: "national" };
const pillow: Parcel = { grams: 800, l: 60, w: 40, h: 40, zone: "local" };
console.log("StandardPost book :", shippingCost("StandardPost", book));
console.log("BoxFlat pillow :", shippingCost("BoxFlat", pillow));
console.log("expressair book :", shippingCost("expressair", book));
console.log("StandardPost -1 g :", shippingCost("StandardPost", { ...book, grams: -1 }));
Compiled with tsc --strict and run with Node, it printed:
StandardPost book : 120 BoxFlat pillow : 99 expressair book : 0 StandardPost -1 g : 60
- A typo ships for free.
"expressair"falls intodefaultand returns 0, with no error. - Rules leak. The 60 cm pillow still gets BoxFlat’s Rs 99, because the box-size rule is only a comment.
- Bad input gets a price. A parcel of −1 g costs Rs 60. No one validates the parcel, so every branch would have to.
- Every change edits the same function. New rates or a fourth courier reopen this switch, and ExpressAir cannot be tested alone.
Step 3: The design
+--------------------------------+
| ShippingCalculator | context
|--------------------------------|
| - strategies: Map<name, S> |
| + register(s) |
| + quote(courier, parcel) |
| + quoteAll(parcel) / cheapest()|
+---------------+----------------+
| holds many, calls quote() blind
v
+--------------------------------+
| <<interface>> ShippingStrategy|
| courier; quote(Parcel): Quote |
+---+-----------+-----------+----+
^ ^ ^ ^ (added later)
+---------+--+ +------+-----+ +---+------+ +-+----------+
|StandardPost| | ExpressAir | | BoxFlat | |PickupPoint |
| RateCard | | per-kg rate| | flat fee | | locker fee |
+------------+ +------------+ +----------+ +------------+
Parcel (validates itself) --> Quote = priced | unavailable
Refactoring.Guru defines Strategy as a family of algorithms, each in its own class, with interchangeable objects. The context talks to them only through the interface. Here each algorithm is a courier’s pricing rule and the context is ShippingCalculator.
This is polymorphism put to work: one quote() call, different behaviour per class. Rule data goes into each strategy’s constructor, so a quarterly rate change is a new object, not new code. The parking lot episode used one pricing strategy inside a bigger system; here several strategies are compared side by side.
Step 4: The strategy design pattern solution in TypeScript
// Strategy pattern: each courier's pricing rule is its own class behind one interface.
type Zone = "local" | "national";
class Parcel {
constructor(
readonly grams: number,
readonly cm: readonly [number, number, number], // length, width, height
readonly zone: Zone,
) {
if (!Number.isInteger(grams) || grams <= 0) throw new Error(`weight must be a positive whole number of grams, got ${grams}`);
if (cm.some((d) => !Number.isInteger(d) || d <= 0)) throw new Error(`dimensions must be positive whole cm, got ${cm.join("x")}`);
}
get longestSide(): number { return Math.max(...this.cm); }
get volumeCm3(): number { return this.cm[0] * this.cm[1] * this.cm[2]; }
}
// A quote is either a price or a reason; the `ok` field is the discriminant.
type Quote =
| { ok: true; courier: string; paise: number; detail: string }
| { ok: false; courier: string; reason: string };
type PricedQuote = Extract<Quote, { ok: true }>;
interface ShippingStrategy {
readonly courier: string;
quote(parcel: Parcel): Quote;
}
type RateCard = Record<Zone, { basePaise: number; perHalfKgPaise: number }>;
class StandardPost implements ShippingStrategy {
readonly courier = "StandardPost";
constructor(private readonly rates: RateCard, private readonly maxGrams = 20_000) {}
quote(p: Parcel): Quote {
if (p.grams > this.maxGrams) return { ok: false, courier: this.courier, reason: `over ${this.maxGrams / 1000} kg` };
const steps = Math.ceil(p.grams / 500);
const r = this.rates[p.zone];
return { ok: true, courier: this.courier, paise: r.basePaise + steps * r.perHalfKgPaise, detail: `${steps} x 500 g, ${p.zone}` };
}
}
class ExpressAir implements ShippingStrategy {
readonly courier = "ExpressAir";
constructor(private readonly perKgPaise: Record<Zone, number>, private readonly divisor = 5000) {}
quote(p: Parcel): Quote {
const volumetricGrams = Math.ceil((p.volumeCm3 * 1000) / this.divisor); // bulky parcels pay for space
const kg = Math.ceil(Math.max(p.grams, volumetricGrams) / 1000);
const basis = volumetricGrams > p.grams ? "volumetric" : "actual";
return { ok: true, courier: this.courier, paise: kg * this.perKgPaise[p.zone], detail: `${kg} kg ${basis}` };
}
}
class BoxFlat implements ShippingStrategy {
readonly courier = "BoxFlat";
constructor(private readonly flatPaise: number, private readonly maxGrams = 5000, private readonly maxSideCm = 40) {}
quote(p: Parcel): Quote {
if (p.grams > this.maxGrams) return { ok: false, courier: this.courier, reason: `over ${this.maxGrams / 1000} kg` };
if (p.longestSide > this.maxSideCm) return { ok: false, courier: this.courier, reason: `side ${p.longestSide} cm > ${this.maxSideCm} cm box` };
return { ok: true, courier: this.courier, paise: this.flatPaise, detail: "flat box" };
}
}
// The context: knows couriers only through ShippingStrategy, never by class.
class ShippingCalculator {
private readonly strategies = new Map<string, ShippingStrategy>();
constructor(strategies: ShippingStrategy[]) { strategies.forEach((s) => this.register(s)); }
register(s: ShippingStrategy): void {
if (this.strategies.has(s.courier)) throw new Error(`courier already registered: ${s.courier}`);
this.strategies.set(s.courier, s);
}
quote(courier: string, parcel: Parcel): Quote {
const s = this.strategies.get(courier);
if (!s) throw new Error(`unknown courier: ${courier}`);
return s.quote(parcel);
}
quoteAll(parcel: Parcel): Quote[] { return [...this.strategies.values()].map((s) => s.quote(parcel)); }
cheapest(parcel: Parcel): PricedQuote | undefined {
const priced = this.quoteAll(parcel).filter((q): q is PricedQuote => q.ok);
return priced.reduce<PricedQuote | undefined>((best, q) => (!best || q.paise < best.paise ? q : best), undefined); // ties: first registered wins
}
}
// ── demo ─────────────────────────────────────────────────────────────
const rs = (paise: number): string => `Rs ${(paise / 100).toFixed(2)}`;
const price = (q: Quote): string => (q.ok ? rs(q.paise) : "n/a");
const show = (q: Quote): string =>
q.ok ? `${q.courier.padEnd(12)} ${rs(q.paise).padStart(10)} (${q.detail})` : `${q.courier.padEnd(12)} unavailable: ${q.reason}`;
const report = (title: string, calc: ShippingCalculator, p: Parcel): void => {
console.log(`== ${title}`);
calc.quoteAll(p).forEach((q) => console.log(" " + show(q)));
const best = calc.cheapest(p);
console.log(" cheapest -> " + (best ? `${best.courier} ${rs(best.paise)}` : "none"));
};
const tryIt = (label: string, fn: () => unknown): void => {
try { fn(); console.log(` ${label}: accepted`); } catch (e) { console.log(` ${label}: rejected (${(e as Error).message})`); }
};
const Q3: RateCard = { local: { basePaise: 4000, perHalfKgPaise: 1200 }, national: { basePaise: 6000, perHalfKgPaise: 2000 } };
const Q4: RateCard = { local: { basePaise: 4500, perHalfKgPaise: 1300 }, national: { basePaise: 6500, perHalfKgPaise: 2200 } };
const express = new ExpressAir({ local: 5500, national: 9000 });
const calc = new ShippingCalculator([new StandardPost(Q3), express, new BoxFlat(9900)]);
const book = new Parcel(1200, [30, 20, 10], "national");
const pillow = new Parcel(800, [60, 40, 40], "local");
report("Book, 1.2 kg, 30x20x10 cm, national", calc, book);
report("Pillow, 0.8 kg, 60x40x40 cm, local", calc, pillow);
// Quarterly rate change: a new StandardPost instance; ShippingCalculator is untouched.
const q4 = new ShippingCalculator([new StandardPost(Q4), express, new BoxFlat(9900)]);
console.log(`== Q4 rate card: book via StandardPost ${price(calc.quote("StandardPost", book))} -> ${price(q4.quote("StandardPost", book))}`);
// A courier added later: one new class, registered at run time.
class PickupPoint implements ShippingStrategy {
readonly courier = "PickupPoint";
quote(p: Parcel): Quote {
return p.zone === "local" && p.grams <= 10_000
? { ok: true, courier: this.courier, paise: 3500, detail: "collect from locker" }
: { ok: false, courier: this.courier, reason: "local parcels up to 10 kg only" };
}
}
q4.register(new PickupPoint());
report("Pillow again, Q4 + PickupPoint", q4, pillow);
console.log("== Edge cases");
tryIt("parcel of 0 g", () => new Parcel(0, [10, 10, 10], "local"));
tryIt("parcel 25x0x5 cm", () => new Parcel(500, [25, 0, 5], "local"));
tryIt("quote from 'expressair'", () => calc.quote("expressair", book));
tryIt("register BoxFlat twice", () => calc.register(new BoxFlat(8900)));
const anvil = new Parcel(25_000, [30, 30, 30], "national");
console.log(" 25 kg anvil, national: " + calc.quoteAll(anvil).map((q) => `${q.courier} ${price(q)}`).join(", "));
const lonely = new ShippingCalculator([new BoxFlat(9900)]);
console.log(" only BoxFlat, 25 kg anvil -> cheapest: " + (lonely.cheapest(anvil)?.courier ?? "none"));
- The interface is the contract. A TypeScript
implementsclause checks that a class fits the interface. A test class with noquote()failed to compile with error TS2420. - Unavailable is a value, not a crash.
Quoteis a discriminated union: checkingq.oknarrows it, so the compiler only lets you readpaiseon a priced quote. - Rates are data. Q3 and Q4 are two
RateCardobjects for the same class. - The context guards names. Unknown or duplicate couriers throw. On a tie,
cheapest()keeps the first registered courier, since aMapiterates in insertion order. - The parcel validates itself in one constructor (encapsulation), so no strategy repeats the check.
Step 5: Run it and check the output
== Book, 1.2 kg, 30x20x10 cm, national StandardPost Rs 120.00 (3 x 500 g, national) ExpressAir Rs 180.00 (2 kg actual) BoxFlat Rs 99.00 (flat box) cheapest -> BoxFlat Rs 99.00 == Pillow, 0.8 kg, 60x40x40 cm, local StandardPost Rs 64.00 (2 x 500 g, local) ExpressAir Rs 1100.00 (20 kg volumetric) BoxFlat unavailable: side 60 cm > 40 cm box cheapest -> StandardPost Rs 64.00 == Q4 rate card: book via StandardPost Rs 120.00 -> Rs 131.00 == Pillow again, Q4 + PickupPoint StandardPost Rs 71.00 (2 x 500 g, local) ExpressAir Rs 1100.00 (20 kg volumetric) BoxFlat unavailable: side 60 cm > 40 cm box PickupPoint Rs 35.00 (collect from locker) cheapest -> PickupPoint Rs 35.00 == Edge cases parcel of 0 g: rejected (weight must be a positive whole number of grams, got 0) parcel 25x0x5 cm: rejected (dimensions must be positive whole cm, got 25x0x5) quote from 'expressair': rejected (unknown courier: expressair) register BoxFlat twice: rejected (courier already registered: BoxFlat) 25 kg anvil, national: StandardPost n/a, ExpressAir Rs 2250.00, BoxFlat n/a only BoxFlat, 25 kg anvil -> cheapest: none
Tested: TypeScript 7.0.2 on Node v22.23.5 — tsc --strict --target es2022 --module commonjs main.ts && node main.js, 2026-11-27. Output above is copied from that run.
The 0.8 kg pillow is 96,000 cm³, so ExpressAir bills it as 20 kg. A separate assert run checked the 500/501 g and 5,000/5,001 g boundaries.
Why this design works
- Open/closed. PickupPoint and the Q4 rates arrived with zero edits to
ShippingCalculator. Episode 10 covers the open/closed principle on its own. - One reason to change per class. A StandardPost rate change touches StandardPost only, which follows the single responsibility principle.
- Composition over inheritance. The calculator has strategies, as Wikipedia describes; nothing subclasses a “base courier”.
- Each rule is testable alone. Build one
BoxFlatand test its limits.
Trade-offs, edge cases and when not to use it
| Option | Good when | Cost |
|---|---|---|
switch in one function |
Two or three short rules that rarely change | Every change edits it; a missed case can return a silent default |
| Strategy classes (this episode) | Rules change on their own schedule, carry config, or are added over time | More types; the caller must know which strategies exist to register them |
| Strategy as a function | A rule is one small formula with no config | No name or extra methods unless you add them; harder to log and list |
| Rules in a config table | All couriers share one formula shape, only numbers differ | Breaks as soon as one courier needs a different formula, like volumetric weight |
Two edge cases stay open. ExpressAir has no weight limit, so it prices the 25 kg anvil. And cheapest() returns undefined when no courier can ship, which the caller must handle. With a couple of rarely changing rules, the pattern is overkill. My recommendation: keep the switch until two rules change on different schedules.
Interview follow-up questions
How is the strategy pattern different from the state pattern?
The structure looks almost the same: a context holding an object behind an interface. The intent differs. In Strategy the client picks the algorithm from outside, and strategies do not know each other. In State, behaviour follows the object’s lifecycle, and states may switch the context to the next state, as Baeldung’s comparison explains. The state design pattern gets its own episode.
Who picks the strategy, and how would you add a festive surcharge?
Not the context. A config file or a factory builds the strategies at the edge, and cheapest() or the user picks one per order. For a surcharge, wrap any strategy in an object that implements ShippingStrategy, calls the inner quote() and adds 10%. That wrapper is the decorator pattern; no courier class changes.
How would you test this and keep it safe under load?
Test each strategy with boundary parcels: 500 and 501 g, 40 and 41 cm. Test the calculator with a stub strategy and assert on unknown names, duplicates and ties. Strategies hold only readonly config, so one instance can serve many requests. Change rates by swapping in a new calculator, not by mutating a live one.
The same solution in PHP
Show the PHP version
<?php
declare(strict_types=1);
final readonly class Parcel
{
/** @param array{int,int,int} $cm length, width, height */
public function __construct(public int $grams, public array $cm, public string $zone)
{
if ($grams <= 0) throw new InvalidArgumentException("weight must be positive grams, got $grams");
if (min($cm) <= 0) throw new InvalidArgumentException('dimensions must be positive cm');
if (!in_array($zone, ['local', 'national'], true)) throw new InvalidArgumentException("unknown zone $zone");
}
public function volumeCm3(): int { return $this->cm[0] * $this->cm[1] * $this->cm[2]; }
}
final readonly class Quote
{
private function __construct(public string $courier, public ?int $paise, public string $note) {}
public static function priced(string $c, int $paise, string $detail): self { return new self($c, $paise, $detail); }
public static function unavailable(string $c, string $reason): self { return new self($c, null, $reason); }
public function __toString(): string
{
return $this->paise === null
? sprintf('%-12s unavailable: %s', $this->courier, $this->note)
: sprintf('%-12s %10s (%s)', $this->courier, rs($this->paise), $this->note);
}
}
interface ShippingStrategy
{
public function courier(): string;
public function quote(Parcel $p): Quote;
}
final class StandardPost implements ShippingStrategy
{
/** @param array<string, array{int,int}> $rates zone => [base paise, paise per 500 g] */
public function __construct(private readonly array $rates) {}
public function courier(): string { return 'StandardPost'; }
public function quote(Parcel $p): Quote
{
if ($p->grams > 20_000) return Quote::unavailable($this->courier(), 'over 20 kg');
$steps = intdiv($p->grams + 499, 500);
[$base, $step] = $this->rates[$p->zone];
return Quote::priced($this->courier(), $base + $steps * $step, "$steps x 500 g, {$p->zone}");
}
}
final class ExpressAir implements ShippingStrategy
{
/** @param array<string, int> $perKg zone => paise per kg */
public function __construct(private readonly array $perKg) {}
public function courier(): string { return 'ExpressAir'; }
public function quote(Parcel $p): Quote
{
$volumetric = intdiv($p->volumeCm3() * 1000 + 4999, 5000);
$kg = intdiv(max($p->grams, $volumetric) + 999, 1000);
$basis = $volumetric > $p->grams ? 'volumetric' : 'actual';
return Quote::priced($this->courier(), $kg * $this->perKg[$p->zone], "$kg kg $basis");
}
}
final class BoxFlat implements ShippingStrategy
{
public function __construct(private readonly int $flatPaise) {}
public function courier(): string { return 'BoxFlat'; }
public function quote(Parcel $p): Quote
{
if ($p->grams > 5000) return Quote::unavailable($this->courier(), 'over 5 kg');
if (max($p->cm) > 40) return Quote::unavailable($this->courier(), 'side ' . max($p->cm) . ' cm > 40 cm box');
return Quote::priced($this->courier(), $this->flatPaise, 'flat box');
}
}
final class ShippingCalculator
{
/** @var array<string, ShippingStrategy> */
private array $strategies = [];
public function __construct(ShippingStrategy ...$strategies) { foreach ($strategies as $s) $this->register($s); }
public function register(ShippingStrategy $s): void
{
if (isset($this->strategies[$s->courier()])) throw new LogicException("courier already registered: {$s->courier()}");
$this->strategies[$s->courier()] = $s;
}
/** @return list<Quote> */
public function quoteAll(Parcel $p): array { return array_map(fn (ShippingStrategy $s) => $s->quote($p), array_values($this->strategies)); }
public function cheapest(Parcel $p): ?Quote
{
$best = null;
foreach ($this->quoteAll($p) as $q) {
if ($q->paise !== null && ($best === null || $q->paise < $best->paise)) $best = $q;
}
return $best;
}
}
function rs(int $paise): string { return 'Rs ' . number_format($paise / 100, 2, '.', ''); }
$calc = new ShippingCalculator(
new StandardPost(['local' => [4000, 1200], 'national' => [6000, 2000]]),
new ExpressAir(['local' => 5500, 'national' => 9000]),
new BoxFlat(9900),
);
foreach (['Book, 1.2 kg, 30x20x10 cm, national' => new Parcel(1200, [30, 20, 10], 'national'),
'Pillow, 0.8 kg, 60x40x40 cm, local' => new Parcel(800, [60, 40, 40], 'local')] as $title => $parcel) {
echo "== $title\n";
foreach ($calc->quoteAll($parcel) as $q) echo " $q\n";
$best = $calc->cheapest($parcel);
echo ' cheapest -> ' . ($best ? "{$best->courier} " . rs((int) $best->paise) : 'none') . "\n";
}
try { new Parcel(0, [10, 10, 10], 'local'); } catch (InvalidArgumentException $e) { echo " 0 g parcel: rejected ({$e->getMessage()})\n"; }
== Book, 1.2 kg, 30x20x10 cm, national StandardPost Rs 120.00 (3 x 500 g, national) ExpressAir Rs 180.00 (2 kg actual) BoxFlat Rs 99.00 (flat box) cheapest -> BoxFlat Rs 99.00 == Pillow, 0.8 kg, 60x40x40 cm, local StandardPost Rs 64.00 (2 x 500 g, local) ExpressAir Rs 1100.00 (20 kg volumetric) BoxFlat unavailable: side 60 cm > 40 cm box cheapest -> StandardPost Rs 64.00 0 g parcel: rejected (weight must be positive grams, got 0)
PHP 8.3.6 uses a PHP interface, which a class must implement in full or PHP raises a fatal error. Parcel and Quote are readonly classes (PHP 8.2+). Prices match the TypeScript run.
Practice: extend it yourself
- Write a
Surchargeclass that implementsShippingStrategy, wraps another strategy and adds a percentage (round to whole paise). Expected behaviour: StandardPost with Q3 rates plus 10% quotes the book at Rs 132.00, and no existing class changes. - Add
daysto priced quotes (StandardPost 2 local / 5 national, ExpressAir 1, BoxFlat 4) and afastest()method. Expected behaviour: the book’s fastest option is ExpressAir at Rs 180.00, whilecheapest()still returns BoxFlat at Rs 99.00. - Add a
fromFunction(courier, fn)helper that turns a plain function into aShippingStrategy. Expected behaviour: a function-based “LocalBike” courier (Rs 30.00, local only) registers and quotes exactly like a class-based one.
- The strategy design pattern puts each interchangeable algorithm in its own class behind one interface.
- The context calls the interface and never checks which concrete strategy it holds.
- Pass rule data such as rate cards into strategy constructors, so a rate change is a new object, not new code.
- Return “unavailable with a reason” as a value; a silent default price is the bug the switch version had.
- Strategy and State share a structure; in Strategy the client chooses, in State the lifecycle does.
Frequently Asked Questions
What is the strategy design pattern?
A behavioural pattern from the 1994 Gang of Four book, also called the policy pattern. Each interchangeable algorithm sits in its own class behind one interface, and a context calls that interface without knowing the class. Here each courier's pricing rule is one strategy.
When should I use the strategy pattern instead of if/else?
When the branches are whole algorithms that change on their own schedule, grow over time, or need testing alone, like quarterly shipping rules. Keep the if/else for two or three short branches that rarely change; Refactoring.Guru calls the extra classes not worth it there.
What are the parts of the strategy pattern?
The strategy interface declares one operation, here quote(parcel). Concrete strategies implement it: StandardPost, ExpressAir and BoxFlat. The context, ShippingCalculator, holds strategies and calls them through the interface. Client code decides which strategies to build and register.
Can a strategy be a plain function in TypeScript?
Yes. A function of type (parcel: Parcel) => Quote is a valid strategy, and Refactoring.Guru names anonymous functions as the lighter option. Use classes when a strategy carries configuration such as a rate card, or needs a name to register and log.
Does the strategy pattern follow the open/closed principle?
Yes. A new courier is one new class, registered at run time; the calculator does not change. In this episode PickupPoint was added later and changed the cheapest() result with no edit to ShippingCalculator.
References
- Refactoring.Guru — Strategy
- Wikipedia — Strategy pattern
- Baeldung — State vs Strategy pattern
- TypeScript Handbook — Classes (implements, readonly)
- TypeScript Handbook — Narrowing (discriminated unions)
- TypeScript Handbook — Type Compatibility (structural typing)
- MDN Web Docs — Map
- PHP Manual — Object Interfaces
- PHP Manual — The Basics (readonly classes)
