Strategy Pattern
Learn how to put interchangeable rules into their own classes behind one interface, using parking fees as the example, and how Java lambdas make strategies short.
Imagine you want to travel from your home to the airport. You can go by bus, by taxi, by metro or on your own bike. The goal is always the same: reach the airport. But the way you do it, the strategy, depends on the time, the money and the traffic. Today you take the metro, tomorrow, because of luggage, you take a taxi. You can change your choice without changing where you are going.
The Strategy pattern brings this to code. When a program has several ways of doing the same job, you put each way in its own class, give them all the same interface, and let the main code use whichever one it is given. You have already met the idea twice in this track: the Notifier example in the first lesson and the discount example in the Open/Closed lesson. Here we study it properly. It is the first of the behavioral patterns, the group that is about how objects behave and talk to each other.
01The problem: many rules inside one method
A parking lot charges fees. Different customers have different price plans: an hourly rate, a flat daily rate, and a cheaper weekend rate. A first version puts all of them into one method:
public class FeeCalculator {
public long feeInCents(String plan, long minutesParked) {
if (plan.equals("HOURLY")) {
long hours = (minutesParked + 59) / 60; // round up to the next hour
return hours * 200;
} else if (plan.equals("FLAT")) {
return 1500;
} else if (plan.equals("WEEKEND")) {
long hours = (minutesParked + 59) / 60;
return hours * 120;
}
throw new IllegalArgumentException("Unknown plan: " + plan);
}
}This is fine for three plans. But think about the next year: a monthly pass, an early-bird discount, an electric-vehicle rate, a festival offer. Every one is another branch, and the method becomes a long, risky tangle:
- Each new plan means editing a method that already works, which can break the others.
- The rules for different plans are mixed together, so a change for one plan needs care to avoid touching another.
- The class is hard to test, because you must go through the
planstring every time. - The calculator cannot easily change the plan at run time or take a plan chosen by a user.
Loading the rest of the lesson…