Strategy Pattern
The Strategy pattern: putting each interchangeable algorithm behind one interface so the caller chooses it, and why in Python the strategy is often a function.
A checkout charges for shipping differently by carrier, a sort orders the same list by title or by year, and a shop applies a different discount to each customer. Each is one job with several interchangeable ways of doing it. The Strategy pattern puts each way behind one interface, so the code that does the job holds whichever one the caller hands it, and a new way is a new class rather than a new branch.
This topic opens on the if chain that the pattern replaces, then reads the participants off the class diagram, where a context holds a strategy. The template swaps one strategy for another on the same context in Python, Java and TypeScript.
Two examples follow: shipping costs for three carriers at a checkout, and the sort functions of two standard libraries, Java's Comparator and Python's sorted(key=). A comparison sets a strategy class beside a plain function in Python, and says when each fits. The gotcha is a context that still checks which strategy it holds, and the exercise writes three discount rules both ways.
By the end you can recognise a strategy, implement one as a class or a function, and spot a context that has undone it.
Contents
9 cardsnot started