A ticket machine is a C++ simulation that sells stadium tickets while tracking inventory, inserted-card status, card validity, and its current operational state. Its actions include inserting a card, checking validity, taking a ticket, and removing a card. section 13.1 section 13.1.2
The machine recognizes four named states:
- READY accepts a card and can reject inappropriate actions. section 13.1
- VALIDATING checks whether the inserted card is valid, permits removal before validation, and can return to READY. section 13.1
- TICKET_SOLD waits for the customer to take the ticket, then decrements the ticket count. section 13.1
- SOLD_OUT refuses sales and handles card removal without selling another ticket. section 13.1
A straightforward implementation puts a switch over all four states inside every action method. That duplicates state-dependent logic and makes changes leak across insert, validate, take, and remove operations. The State Design Pattern moves each state's behavior into a State subclass. TicketMachine delegates actions to its current State object, whose methods return the next state; this improves encapsulation and loosens coupling. section 13.1.2 section 13.1.3
A purchase interaction
Starting with three tickets, inserting a card moves READY to VALIDATING. Checking validity can move to TICKET_SOLD; taking the ticket prints a confirmation, reduces the count to two, and returns to READY. Removing a card during validation cancels the sale and returns to READY.
Figure 13.1 A UML state diagram showing the four states and the state transitions of an automatic ticket machine. The machine keeps track of the number of tickets it has, whether there is a credit card inserted, and the validity status of the card. Customer and machine actions (numbered; e.g., 1: insert card) or certain conditions (in square brackets; e.g., [card invalid]) can cause transitions from one state to another. This figure only shows the actions that cause transitions.
The state diagram maps customer actions and machine conditions to transitions among READY, VALIDATING, TICKET_SOLD, and SOLD_OUT. section 13.1
