Part 3 of 6 · 2 min read
The structure
Strategy, concrete strategies and context.
GoF names three parts. The Strategy is the common interface. Each ConcreteStrategy implements one algorithm. The Context holds a reference to a strategy and calls it. The context is configured with a concrete strategy.
interface FeeStrategy { long fee(int minutes); }
class Hourly implements FeeStrategy {
public long fee(int m) { return ((m + 59) / 60) * 20L; }
}
class FlatDay implements FeeStrategy {
public long fee(int m) { return 100; }
}
class FreeFirstHour implements FeeStrategy {
public long fee(int m) { return Math.max(0, (m - 60 + 59) / 60) * 20L; }
}
class ParkingLot {
private FeeStrategy strategy;
ParkingLot(FeeStrategy s) { strategy = Objects.requireNonNull(s); }
void setStrategy(FeeStrategy s) { strategy = Objects.requireNonNull(s); }
long checkout(int minutes) { return strategy.fee(minutes); }
}
With new ParkingLot(new Hourly()), checkout(130) returns 60. After setStrategy(new FlatDay()) it returns 100. After setStrategy(new FreeFirstHour()), 130 minutes cost 40 (two chargeable hours) and 50 minutes cost 0.
ParkingLot never names a concrete fee class and has no switch. A new rule is a new class, and the old classes are untouched. This is the open-closed principle at work. The strategy is also passed in from outside, which is dependency injection (Level 3, module 6). A strategy can be replaced while the program runs, which a subclass cannot do.
Context
The context is the object that uses a strategy. It holds the strategy and delegates the varying work to it.
Example: ParkingLot, which asks its FeeStrategy for the fee.
Check yourself:
1. What does checkout(50) return with FreeFirstHour?
2. Which class is the context?
3. Why can a strategy be swapped but a subclass cannot?