O'Reilly logo

C# 3.0 Design Patterns by Judith Bishop

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

State Pattern

Role

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.

Illustration

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.

State pattern illustration—frequent flyer program

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. When the State for a traveler changes, the behavior ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required