Design Patterns «Prev Next»

Abstract Traffic Signal Java Exercise

Course Project, Part 2

Objective: Implement a traffic-signal abstraction whose public operations preserve the legal state-transition order.

Create an abstract TrafficSignal class with three states: STOP, GO, and CAUTION. A signal starts at STOP and advances only in this cycle:

STOP -> GO -> CAUTION -> STOP

Do not expose a public method that permits an arbitrary state assignment. The transition operation owns the invariant.

UML diagram of the TrafficSignal class
UML diagram of the TrafficSignal abstraction.

Requirements

  1. Represent the three states with an enum or named constants.
  2. Provide requestPassage(). A request is recorded only while the signal is stopped.
  3. Provide changeState(). Entering GO automatically clears a pending passage request.
  4. Expose read-only access to the current state and request flag.
  5. Declare an abstract getMessage() method.
  6. Create TrafficLight and WalkSign subclasses that return the appropriate message for each state.
  7. Add tests that exercise one complete state cycle and the passage-request rule.

Design Questions