Skip to the guide

State

IntermediatePattern7 pages

State gives each condition of an object its own class, and the object hands every call to the class for its current condition. The 1994 book Design Patterns gives its intent as "allow an object to alter its behavior when its internal state changes. The object will appear to change its class." Interviewers listen for who decides the next state, and for when a field is enough.

The card on a hotel's front desk

Think of the receptionist at a small hotel. Guests ask her the same few things all day: check me in, give me a late checkout, call me a taxi. A card on the desk tells her how to answer, and there is one card for each situation, such as "day", "night" and "fire drill". Each card lists the requests it accepts and what to do about them, and at the bottom it says which card comes next. When the hotel adds a "full house" card, nobody reprints the other cards.

In code, the receptionist is this page's Download, and a guest's request is a call such as pause(). The layout that every card shares is the abstract class DownloadState. Each card is one state class, such as Downloading or Paused, and the line at the bottom of a card is the next state that a method returns. The "full house" card is a new state class. A request a card doesn't list gets a polite no, which is a refusal from the parent class.