Strategy Pattern
Low-Level Design: lesson 6 of 10
Put the part that varies in its own object and swap it at runtime.
Lesson 6 of 10 · 5 min
Strategy Pattern
Step 1 of 11
stage time—
Same car, same driver, same stage. Only one step varies: how much grip today.
The Idea
Find the one step that keeps changing, lift it into its own object with a fixed method name, and have the surrounding workflow call it. The workflow stops caring which variant is loaded, and adding a sixth variant never reopens it.
Real-World Example
Rally tyres. Same car, same driver, same stage — but slicks, wets or gravel go on the morning of the run, decided by the weather. Nobody builds a separate car per surface; the swappable part is bolted on last.
The Code
def slicks(base): return base * 1.0 # dry: full grip
def wets(base): return base * 0.8 # safe in rain, slower
def gravel(base): return base * 0.6
class Stage:
def __init__(self, tyres): self.tyres = tyres # the swappable step
def time(self, base): return round(120 / self.tyres(base), 2)
s = Stage(slicks)
print(s.time(1)) # 120.0
s.tyres = wets # swapped between runs; Stage untouched
print(s.time(1)) # 150.0
print(Stage(gravel).time(1)) # 200.0
Your turn
What does this print?
def loud(s): return s.upper()
def quiet(s): return s.lower()
class Speaker:
def __init__(self, style): self.style = style
def say(self, s): return self.style(s)
sp = Speaker(loud)
out = [sp.say("Go")]
sp.style = quiet
out.append(sp.say("Go"))
print(out)Mini quiz
1 / 3