State / Control• Patterns: State, Singleton
Traffic Signal
Easy
Problem Summary
Design a Traffic Signal Controller that transitions between Red, Yellow, and Green states with dynamic durations.
Functional Scope
- Maintain active signal light status (Red, Yellow, Green).
- Process state transitions sequentially: Red -> Green -> Yellow -> Red.
- Allow dynamic duration override configurations for active states.
Entity-Relationship (ER) Schema
TrafficSignalController [1] <---> [*] TrafficLight TrafficLight [1] <---> [1] SignalState
Design Approach
Use the State pattern to prevent massive switch-case statements. Each state holds its display rules and references the next state in sequence.
Core Classes & Models
TrafficLight (Context class)SignalState (State interface)RedState, GreenState, YellowState (Concrete states)TrafficSignalController (Singleton orchestrating intersections)
Code Blueprint
public interface SignalState {
void changeState(TrafficLight light);
int getDuration();
}
public class RedState implements SignalState {
public void changeState(TrafficLight l) { l.setState(new GreenState()); }
public int getDuration() { return 30; }
}