DELAPARRA
Index
Color
NL
Category: Design patterns

Strategy

Explained by Updated

What is Strategy?

Strategy: Define a family of algorithms, encapsulate each one, and make them interchangeable — the algorithm varies independently from clients that use it. The Strategy pattern defines a family of interchangeable algorithms behind one interface. The code that uses them picks one at runtime without knowing its details. Shipping costs are a typical example. A ShippingCalculator interface with implementations for PostNL, DHL and pick-up lets the checkout call calculate($order) on whichever applies. Adding a new carrier means adding a class, not editing checkout logic.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about Strategy

What should you keep in mind with Strategy?

It replaces long if and switch blocks that choose behaviour based on a type, and makes each variant easy to test in isolation. Laravel uses the idea in its drivers for mail, cache and storage. Only introduce it when there really are several variants; for a single algorithm, a plain function is simpler and just as easy to change later.

At a glance

CategoryDesign patterns
Explained by
Updated

More Design patterns terms

All terms starting with S

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.