Part 2 of 6 · 2 min read
The idea
Put each algorithm in its own class.
Think of a satnav that offers "fastest", "shortest" and "avoid tolls". The map and the car stay the same. Only the way of choosing the route changes. The driver picks one, and may switch half way.
A parking lot has the same shape. The checkout code is fixed, but the fee rule differs: hourly, flat per day, or free for the first hour. A first version often puts the rules in one method.
static long fee(String kind, int minutes) {
switch (kind) {
case "HOURLY": return ((minutes + 59) / 60) * 20L;
case "FLAT": return 100;
default: throw new IllegalArgumentException(kind);
}
}
For 130 minutes the hourly rule rounds up to 3 hours and charges 60 (at 20 per hour, made up). The code works, but each new rule means editing this method, and the same switch tends to spread to other places.
GoF's intent for Strategy is to define a family of algorithms, put each one in its own class, and make them interchangeable, so that the algorithm can vary independently of the clients that use it. GoF's motivating example is a text editor that can break text into lines in several ways. Hard-wiring every algorithm into the class that needs it makes that class bigger and harder to maintain, and adding or changing an algorithm becomes difficult.
HF reaches the same idea from its first chapter, with a duck simulator. The flying behaviour varies between duck types. HF's design advice is to find the parts that vary and set them apart from what stays the same. It adds a second rule, to program to an interface and not to an implementation.
Strategy pattern
The Strategy pattern puts each way of doing a job in its own class behind a common interface, so the object that needs the job done can use any of them.
Example: Hourly, FlatDay and FreeFirstHour, all behind a FeeStrategy interface.
Check yourself: 1. What changes and what stays the same in the parking lot? 2. What does the hourly rule charge for 130 minutes? 3. What are HF's two design rules here?