The next pattern in this group, the State pattern, can be seen as a dynamic version of the Strategy pattern. When the state inside an object changes, it can change its behavior by switching to a set of different operations. This is achieved by an object variable changing its subclass, within a hierarchy.
Consider a frequent flyer program run by an airline. A traveler starts out at, say, Blue level; then, as miles are accumulated by flying, she moves up to Silver or Gold level. At these levels, travelers can access lounges, get an extra baggage allowance, and also earn miles at a faster rate. For example, at the Silver tier, for every 1000 miles flown, a credit for 1250 miles is earned; at the Gold level, the credit is for 1500 miles. Other benefits also apply, as shown in the sample from South African Airways in Figure 7-3.
Figure 7-3. State pattern illustration—frequent flyer program
A frequent flyer program works in annual cycles: at the end of each year, a member's activity is calculated for the year and she is assigned to a tier. In the case of our hypothetical program, one of the requirements is to fly 25,000 miles in one year to attain Silver status and keep it for the next year; for Gold status a member must fly 50,000 miles.
So, in this illustration, the
State is the member's level in the program.
State for a traveler changes, the behavior ...