Strategy and factory
| Strategy | |
| Simple factory | |
| Replace switch | |
| When patterns pay |
Strategy
A strategy hides one varying rule behind a shared interface, so the caller never learns which variant runs. Adding a new discount means adding a class, not editing every checkout branch.
interface Discount { public function apply(float $total): float; } class VipDiscount implements Discount { public function apply(float $total): float { return $total * 0.9; } }
Simple factory
A factory keeps object creation in one named place instead of scattering new calls across the codebase. Callers ask for a kind and receive a ready strategy without knowing class names.
function makeDiscount(string $kind): Discount { if ($kind === "vip") { return new VipDiscount(); } throw new InvalidArgumentException("Unknown kind: " . $kind); }
Replace switch
Long switches on the same kind string are factories crying for help. Build the object once at the edge, then let polymorphism carry the value through the rest of the flow.
$discount = makeDiscount($kind); $total = $discount->apply(200.0); echo $total . "\n";
When patterns pay
Patterns cost files and names, so spend them where variants multiply: pricing rules, shipping rules, export formats. With one variant only, a plain function wins. With three or more, strategies and factories pay rent.
function checkoutTotal(string $kind, float $total): float { return makeDiscount($kind)->apply($total); } echo checkoutTotal("vip", 200.0) . "\n";
Next: Repository and observer
Article author: Arthur Isaev