Traffic Signal System - Observer Pattern Implementation
This is an implementation of the Observer design pattern for a Smart City traffic intersection where vehicles and pedestrians react differently to the same signal changes.
Problem Statement
Designing software for a Smart City intersection where a traffic signal changes colors (RED, GREEN) and different types of observers must react appropriately. The unique challenge here is that unlike typical observer patterns where all observers handle updates similarly, vehicles and pedestrians have opposite behaviors for the same signal state.
Key Challenge:
- When signal is GREEN → Cars GO, Pedestrians WAIT
- When signal is RED → Cars STOP, Pedestrians WALK
Class Diagram
+------------------+ +-----------------------+
| Subject | | Observer |
| (Interface) | | (Interface) |
+------------------+ +-----------------------+
| + add(obs) | | + update(color) |
| + remove(obs) | +-----------+-----------+
| + notify() | ^
+--------+---------+ |
^ | (Implements)
| (Implements) |
| |
+--------+---------+ +-----------+-----------+----------------+
| SignalStation |<>---------->| | |
+------------------+ (List) | +----------------+ | +----------+ |
| - observers List | | | VehicleObserver| | |WalkObserver| |
| - signalColor | | +----------------+ | +----------+ |
| + updateSignal() | | | - name | | | -name | |
+------------------+ | | + update() | | | +update() | |
| +----------------+ | +----------+ |
+-----------------------+----------------+
Implementation
package observer.trafficsignalsystem;
import java.util.ArrayList;
import java.util.List;
/**
* Main system demonstrating the Observer Pattern for traffic control.
* Vehicles and Pedestrians react differently to the same signal change.
*/
public class TrafficSignalSystem {
/**
* Enum defining the possible states of a traffic signal.
*/
enum SignalColor {
GREEN,
RED
}
/**
* Observer interface for any entity reacting to traffic lights.
*/
interface Observer {
/**
* Triggered when the signal color changes.
*/
void update(SignalColor signalColor);
}
/**
* Subject interface for managing subscriptions.
*/
interface Subject {
void addObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
/**
* Concrete Subject acting as the Traffic Signal Station.
*/
static class SignalStation implements Subject {
private final List<Observer> observers = new ArrayList<>();
private SignalColor signalColor;
@Override
public void addObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(signalColor);
}
}
/**
* Updates the signal color and triggers notification.
*/
public void updateTrafficSignal(SignalColor signalColor) {
this.signalColor = signalColor;
System.out.println("\n[SignalStation] Signal changed to: " + signalColor);
notifyObservers();
}
}
/**
* Concrete Observer representing a Vehicle.
* Stops on RED, Moves on GREEN.
*/
static class VehicleObserver implements Observer {
private final String name;
public VehicleObserver(String name) {
this.name = name;
}
@Override
public void update(SignalColor signalColor) {
if (signalColor == SignalColor.GREEN) {
System.out.println(" [Car] " + name + ": Green Light! Vroom Vroom...");
} else {
System.out.println(" [Car] " + name + ": Red Light! Screech... Stop.");
}
}
}
/**
* Concrete Observer representing a Pedestrian.
* Stops on GREEN, Moves on RED.
*/
static class WalkObserver implements Observer {
private final String name;
public WalkObserver(String name) {
this.name = name;
}
@Override
public void update(SignalColor signalColor) {
if (signalColor == SignalColor.GREEN) {
System.out.println(" [Walker] " + name +
": Green Light! Wait for cars.");
} else {
System.out.println(" [Walker] " + name +
": Red Light! Safe to cross.");
}
}
}
/**
* Main driver method to simulate the traffic signal logic.
*/
public static void main(String[] args) {
SignalStation suratTrafficStation = new SignalStation();
System.out.println("\n----Simulation Started----\n");
Observer walker1 = new WalkObserver("Shiv");
Observer car1 = new VehicleObserver("BMW");
suratTrafficStation.addObserver(walker1);
suratTrafficStation.addObserver(car1);
System.out.println("\n------- Signal -> GREEN -------");
suratTrafficStation.updateTrafficSignal(SignalColor.GREEN);
System.out.println("\n------- Signal -> RED -------");
suratTrafficStation.updateTrafficSignal(SignalColor.RED);
}
}
Key Features
- Observer Pattern: Implements one-to-many dependency for traffic signal updates
- Opposite Behaviors: Different observers react differently to the same event
- Type Safety: Uses Enum for signal colors instead of strings
- Extensible: Easy to add new observer types (Bicycles, Emergency Vehicles, etc.)
- Real-time Coordination: All observers receive updates simultaneously
- Loose Coupling: SignalStation doesn't need to know about specific observer implementations
How It Works
- Subject (SignalStation): Maintains the current signal color and list of observers
- Observers (VehicleObserver, WalkObserver): Implement different logic for the same signal state
-
Registration: Vehicles and pedestrians register using
addObserver() -
State Change: When signal changes via
updateTrafficSignal(), all observers are notified - Custom Logic: Each observer type implements its own behavior based on the signal color
Sample Output
----Simulation Started----
------- Signal -> GREEN -------
[SignalStation] Signal changed to: GREEN
[Walker] Shiv: Green Light! Wait for cars.
[Car] BMW: Green Light! Vroom Vroom...
------- Signal -> RED -------
[SignalStation] Signal changed to: RED
[Walker] Shiv: Red Light! Safe to cross.
[Car] BMW: Red Light! Screech... Stop.
Real-World Applications
- Smart City traffic management systems
- Autonomous vehicle coordination
- Pedestrian crossing safety systems
- Emergency vehicle priority signaling
- Traffic flow optimization
- Intersection collision avoidance
Extensions
This pattern can be extended to support:
- ORANGE/YELLOW signals for warning states
- Emergency vehicles that override normal behavior
- Bicycles with different rules than cars
- Traffic statistics observers that log traffic patterns
- Adaptive signals that adjust timing based on traffic density
Top comments (0)