Strategy: swap how it is done
After this: Replace an if per way of travelling with route classes behind one interface, and swap them in a navigator.
On this page · 7 sections · 3 checks
You are writing a route planner. The user enters a distance, and the app says how many minutes the trip takes. The answer depends on how they travel: a car at 40 km an hour, a bike at 15, or on foot at 5. Next month the owner wants a bus. How do you write it so that each new way to travel is a small change?
The first version: an if per way
Most people start with one function and a branch per way of travelling. Minutes are the distance times 60, divided by the speed, rounded down:
def minutes(km, mode): if mode == "drive": return km * 60 // 40 if mode == "bike": return km * 60 // 15 raise ValueError("unknown mode: " + mode)
print(minutes(12, "drive"))print(minutes(12, "bike"))try: print(minutes(12, "walk"))except ValueError as e: print("error:", e)18 48 error: unknown mode: walk
public class Main { static int minutes(int km, String mode) { if (mode.equals("drive")) { return km * 60 / 40; } if (mode.equals("bike")) { return km * 60 / 15; } throw new IllegalArgumentException("unknown mode: " + mode); }
public static void main(String[] args) { System.out.println(minutes(12, "drive")); System.out.println(minutes(12, "bike")); try { System.out.println(minutes(12, "walk")); } catch (IllegalArgumentException e) { System.out.println("error: " + e.getMessage()); } }}18 48 error: unknown mode: walk
- 12 km by car: 12 × 60 = 720, and 720 divided by 40 is
18. - 12 km by bike: 720 divided by 15 is
48. "walk"matches no branch, so the function reports an error.
This is the code that "SOLID, one principle at a time" warned about. Each new way means opening this function and adding a branch, and each edit can break a way that worked.
Each way in its own class
Here is the idea. Every way of travelling does the same job: given a distance, give the minutes. So give each way its own class with one method, minutes(km), and let the planner hold one of those objects and ask it. The planner no longer knows any speeds.
An object that holds one way of doing a job, and that you can swap for another, is called a . The pattern built around it is the Strategy pattern. Here it has four parts:
| Part | In this program |
|---|---|
| the job, as an interface | RouteStrategy, with minutes(km) |
| one class per way | DriveRoute, BikeRoute, WalkRoute |
| the class that uses a way | Navigator, which holds one route in a field |
| the swap | set_strategysetStrategy, which puts a different route in the field |
Step through the class diagram to see the shape.
Press Run it to build the diagram one step at a time.
- classes
- 0
- relations
- 0
The code
class DriveRoute: def minutes(self, km): return km * 60 // 40
class BikeRoute: def minutes(self, km): return km * 60 // 15
class WalkRoute: def minutes(self, km): return km * 60 // 5
class Navigator: def __init__(self, strategy): self.strategy = strategy
def set_strategy(self, strategy): self.strategy = strategy
def plan(self, km): mins = self.strategy.minutes(km) return f"{type(self.strategy).__name__}: {mins} min"
nav = Navigator(DriveRoute())print(nav.plan(12))nav.set_strategy(BikeRoute())print(nav.plan(12))nav.set_strategy(WalkRoute())print(nav.plan(12))DriveRoute: 18 min BikeRoute: 48 min WalkRoute: 144 min
interface RouteStrategy { int minutes(int km);}
class DriveRoute implements RouteStrategy { public int minutes(int km) { return km * 60 / 40; }}
class BikeRoute implements RouteStrategy { public int minutes(int km) { return km * 60 / 15; }}
class WalkRoute implements RouteStrategy { public int minutes(int km) { return km * 60 / 5; }}
class Navigator { private RouteStrategy strategy;
Navigator(RouteStrategy strategy) { this.strategy = strategy; }
void setStrategy(RouteStrategy strategy) { this.strategy = strategy; }
String plan(int km) { int mins = strategy.minutes(km); return strategy.getClass().getSimpleName() + ": " + mins + " min"; }}
public class Main { public static void main(String[] args) { Navigator nav = new Navigator(new DriveRoute()); System.out.println(nav.plan(12)); nav.setStrategy(new BikeRoute()); System.out.println(nav.plan(12)); nav.setStrategy(new WalkRoute()); System.out.println(nav.plan(12)); }}DriveRoute: 18 min BikeRoute: 48 min WalkRoute: 144 min
Walk through it:
- Each route class has a
minutesmethod with its own speed. In Java they sayimplements RouteStrategy. In Python there is no interface class: any object with aminutesmethod will do, as in "Objects that share behaviour". You could add an abstract base class, as in "Interfaces and polymorphism in design"; the shape is the same. Navigatorgets its first route through the constructor and keeps it in the fieldstrategy.plan(km)asks the route for the minutes with self.strategy.minutes(km)strategy.minutes(km). Then it builds the line from the class name of the route and the minutes. type(self.strategy).__name__strategy.getClass().getSimpleName() gives that class name as text, such asBikeRoute.- set_strategysetStrategy replaces the route in the field. The next
planuses the new one.
The three lines are DriveRoute: 18 min, BikeRoute: 48 min and WalkRoute: 144 min (720 divided by 5). The navigator's code was the same for all three.
One call, step by step
The sequence diagram shows one call after the swap to BikeRoute. Press Run it to send the messages one at a time.
Press Run it to send the messages one at a time.
- messages
- 0
- The user calls
plan(12)on the navigator. - The navigator calls
minutes(12)on the object in its field. It knows only that the object is aRouteStrategy. - The bike route returns
48. - The navigator returns the line
BikeRoute: 48 min.
Run it
The code blocks in this tutorial show Python and Java side by side, but only Python runs in the browser. Java does not run here: read the Java version, or paste it into a Java tool on your computer.
Add a BusRoute at 20 km an hour, swap it in and plan 12 km. It should say BusRoute: 36 min. You did not touch Navigator.
Check yourself
In a chess game the player can change the computer's level (beginner, club player or master) in the middle of a game. Each level picks its next move in its own way. Which pattern fits?
These lines use the route classes and the navigator from this lesson. What do they print?
# the routes and Navigator from this lesson, then:nav = Navigator(WalkRoute())print(nav.plan(3))nav.set_strategy(DriveRoute())print(nav.plan(30))// the routes and Navigator from this lesson, then in main:Navigator nav = new Navigator(new WalkRoute());System.out.println(nav.plan(3));nav.setStrategy(new DriveRoute());System.out.println(nav.plan(30));Complete the first line of plan, so that the navigator asks the strategy it holds for the minutes and keeps the answer in mins. The program should print DriveRoute: 18 min, BikeRoute: 48 min and WalkRoute: 144 min.
class DriveRoute: def minutes(self, km): return km * 60 // 40
class BikeRoute: def minutes(self, km): return km * 60 // 15
class WalkRoute: def minutes(self, km): return km * 60 // 5
class Navigator: def __init__(self, strategy): self.strategy = strategy
def set_strategy(self, strategy): self.strategy = strategy
def plan(self, km): ________ # ← ask the strategy for the minutes return f"{type(self.strategy).__name__}: {mins} min"
nav = Navigator(DriveRoute())print(nav.plan(12))nav.set_strategy(BikeRoute())print(nav.plan(12))nav.set_strategy(WalkRoute())print(nav.plan(12))interface RouteStrategy { int minutes(int km);}
class DriveRoute implements RouteStrategy { public int minutes(int km) { return km * 60 / 40; }}
class BikeRoute implements RouteStrategy { public int minutes(int km) { return km * 60 / 15; }}
class WalkRoute implements RouteStrategy { public int minutes(int km) { return km * 60 / 5; }}
class Navigator { private RouteStrategy strategy;
Navigator(RouteStrategy strategy) { this.strategy = strategy; }
void setStrategy(RouteStrategy strategy) { this.strategy = strategy; }
String plan(int km) { ________ // ← ask the strategy for the minutes return strategy.getClass().getSimpleName() + ": " + mins + " min"; }}
public class Main { public static void main(String[] args) { Navigator nav = new Navigator(new DriveRoute()); System.out.println(nav.plan(12)); nav.setStrategy(new BikeRoute()); System.out.println(nav.plan(12)); nav.setStrategy(new WalkRoute()); System.out.println(nav.plan(12)); }}Honesty notes
- Spot the problem Strategy solves: one function with a branch for each way of doing the same job.
- Put each way into its own class with the same method, behind one interface (RouteStrategy and minutes).
- Write a class that holds one strategy in a field, calls its method, and lets you swap it with a setter.
- Read the Strategy class diagram (a line with a hollow diamond from Navigator to the interface) and its sequence diagram (plan, then minutes, then the answers back).
- Add a new way as a new class, with no edit to the navigator.