Bird
Raised Fist0

Traffic Light System - State Machine, Sensor Input, Emergency Override

LLDmediumInterview freq: medium
Choose your preparation mode4 modes available
▶
Class Trace
Step 1/4
TrafficLight abstract class

TrafficLight is an abstract class holding state (currentState, id) and behavior (changeState).

🎯 Tests if candidate knows abstract class is needed here because Java interfaces cannot hold instance state like currentState.
public abstract class TrafficLight {
    protected State currentState;
    protected String id;
    public abstract void changeState(State newState);
    public State getCurrentState() {
        return currentState;
    }
}
TrafficLightController composition

TrafficLightController composes TrafficLight and StateMachine, owning their lifecycles (composition).

🎯 Tests if candidate understands composition lifecycle: TrafficLight cannot exist independently without controller.
public class TrafficLightController {
    private final TrafficLight trafficLight;
    private final StateMachine stateMachine;
    private final EmergencyDetector emergencyDetector;
    public TrafficLightController() {
        this.trafficLight = new ConcreteTrafficLight();
        this.stateMachine = new ConcreteStateMachine();
        this.emergencyDetector = new EmergencyDetector();
    }
}
StateMachine interface realization

StateMachine is an interface realized by concrete classes to allow extensibility (OCP).

🎯 Tests if candidate knows interface is used here to allow multiple state machine implementations without modifying controller.
public interface StateMachine {
    void transitState();
    State getCurrentState();
}
public class ConcreteStateMachine implements StateMachine {
    private State currentState;
    public synchronized void transitState() {
        // state transition logic
    }
    public State getCurrentState() {
        return currentState;
    }
}
EmergencyDetector association

EmergencyDetector is associated with TrafficLightController but has independent lifecycle (association).

🎯 Tests if candidate distinguishes association (independent lifecycle) from composition in Java relationships.
public class EmergencyDetector {
    public boolean detectEmergency() {
        // sensor detection logic
        return false;
    }
}
public class TrafficLightController {
    private EmergencyDetector emergencyDetector;
    // emergencyDetector can be replaced or shared
}
📐
Class Diagram
Class Diagram
       +----------------------+
       | <<Abstract>>         |
       | TrafficLight         |
       +----------------------+
       | - currentState: State|
       | - id: String         |
       +----------------------+
       | + changeState(State) |
       | + getCurrentState()  |
       +----------------------+
               ◆ composition
               │
       +----------------------------+
       | TrafficLightController     |
       +----------------------------+
       | - trafficLight: TrafficLight|
       | - stateMachine: StateMachine|
       | - emergencyDetector: EmergencyDetector|
       +----------------------------+
       | + synchronized void controlCycle() [sync] |
       | + overrideForEmergency() [sync]            |
       +----------------------------+
               ─ ─ ─► realization
               │
       +----------------------------+
       | StateMachine               |
       +----------------------------+
       | - currentState: State      |
       +----------------------------+
       | + synchronized void transitState() [sync] |
       | + getCurrentState()                      |
       +----------------------------+
               ─ ─ ─► realization
               │
       +----------------------------+
       | EmergencyDetector          |
       +----------------------------+
       | + boolean detectEmergency()|
       +----------------------------+

This diagram shows four key classes in the Traffic Light System design. TrafficLight is an abstract class because it holds mutable state like currentState, which Java interfaces cannot hold. TrafficLightController composes TrafficLight and StateMachine, owning their lifecycles, enforcing strong encapsulation and lifecycle management. StateMachine is an interface realized by concrete classes, enabling the Open-Closed Principle by allowing new state machines without modifying the controller. EmergencyDetector is associated with the controller but has an independent lifecycle, illustrating association versus composition. Synchronization is used on state transition methods to ensure thread safety in concurrent environments. The design balances stateful abstract classes and stateless interfaces to maximize extensibility and maintainability.

Primary Focus

✓ Abstract class vs Interface state + Composition lifecycle + Realization + Singleton volatile

Practice

(1/5)
1. In the Elevator System design, the ElevatorController class uses a private constructor and a static synchronized getInstance() method to provide a single global access point. Which design pattern is applied here and why is it the correct choice?
easy
A. Factory pattern, because it creates ElevatorController instances on demand.
B. Singleton pattern, to ensure only one ElevatorController manages all elevators centrally.
C. Builder pattern, to incrementally construct ElevatorController with complex configuration.
D. Prototype pattern, to clone ElevatorController for each elevator instance.

Solution

  1. Step 1: Identify Singleton usage

    The private constructor and static synchronized getInstance() method restrict instantiation to one object, ensuring a single ElevatorController.
  2. Step 2: Why Singleton fits ElevatorController

    ElevatorController coordinates multiple elevators and floor queues centrally, so multiple instances would cause inconsistent state and scheduling conflicts.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Singleton ensures one global ElevatorController instance [check]
Hint: Singleton restricts to one instance for centralized control [check]
Common Mistakes:
2. In designing a Vehicle abstraction for a parking system, should Vehicle be an abstract class or an interface if it needs to hold state like licensePlate and provide default behavior for getSize()? Why?
easy
A. Abstract class, because it can hold shared state and provide default method implementations.
B. Interface, because it allows multiple inheritance and enforces method contracts without state.
C. Interface, because Java 8+ interfaces can have default methods and fields for state.
D. Abstract class, because it forces all subclasses to implement all methods explicitly.

Solution

  1. Step 1: Analyze state and behavior requirements

    Vehicle needs to hold state (licensePlate) and provide default behavior (getSize), which interfaces cannot hold as fields.
  2. Step 2: Choose abstraction supporting state and default behavior

    Abstract classes support instance variables and method implementations; interfaces cannot hold instance state.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Abstract class supports state and default behavior -> correct choice [check]
Hint: State needs abstract class; interfaces can't hold instance fields [check]
Common Mistakes:
3. You want to add a WeekendFeeStrategy to calculate parking fees differently on weekends. According to SOLID principles, what is the minimum change required in the current design that uses a FeeStrategy interface?
medium
A. Modify the existing FeeStrategy implementation to add weekend logic with an if-statement
B. Add a boolean isWeekend flag to FeeStrategy interface and implement it in all classes
C. Create a new WeekendFeeStrategy class implementing FeeStrategy and inject it where needed without modifying existing classes
D. Create a WeekendFeeStrategy subclass extending the existing FeeStrategy implementation

Solution

  1. Step 1: Identify the SOLID principle involved

    Open-Closed Principle (OCP) requires adding new behavior without modifying existing code.
  2. Step 2: Evaluate options for OCP compliance

    Create a new WeekendFeeStrategy class implementing FeeStrategy and inject it where needed without modifying existing classes respects OCP by adding a new class; Add a boolean isWeekend flag to FeeStrategy interface and implement it in all classes violates OCP by modifying the interface; Modify the existing FeeStrategy implementation to add weekend logic with an if-statement modifies existing code; Create a WeekendFeeStrategy subclass extending the existing FeeStrategy implementation assumes FeeStrategy is a class, not interface.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    New strategy class added without changing existing code [check]
Hint: OCP: add new class, don't modify existing code [check]
Common Mistakes:
4. ElectricCar needs ChargingSpots in the Stack Overflow vehicle analogy. What is the minimum change to support this without modifying existing classes?
hard
A. Add charging logic directly inside existing Spot class with if-else for electric cars
B. Modify Vehicle class to add isElectric flag and add charging logic inside existing methods
C. Create a new ElectricCar class unrelated to Vehicle and a ChargingSpot class unrelated to Spot, manage compatibility externally
D. Add ELECTRIC_CAR to VehicleType enum, CHARGING to SpotType enum, create ElectricCar extends Vehicle, update SpotCompatibility.COMPATIBILITY_MAP accordingly

Solution

  1. Step 1: Identify extensibility without modifying existing classes

    Adding new enum values and subclass ElectricCar extends Vehicle allows extension without changing existing class code.
  2. Step 2: Update compatibility map externally

    Updating SpotCompatibility.COMPATIBILITY_MAP supports new types without modifying core logic, preserving OCP.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Enum extension + subclass + external map update -> minimal change [check]
Hint: Extend enums + subclass + external map -> minimal change [check]
Common Mistakes:
5. ElectricCar requires ChargingSpots in the parking system. What is the minimum change to support this without modifying existing classes, ensuring extensibility and avoiding class explosion?
hard
A. Modify Vehicle class to include a boolean isElectric field and add charging logic inside existing methods.
B. Add charging spot logic inside ParkingLot class and modify parkVehicle() to check for electric cars.
C. Create a new ElectricCarChargingFacade class that extends ParkingLot and handles charging spots separately.
D. Add ELECTRIC_CAR to VehicleType enum, CHARGING to SpotType enum, create ElectricCar subclass, and update SpotCompatibility.COMPATIBILITY_MAP accordingly.

Solution

  1. Step 1: Identify extensibility without modifying existing classes

    Adding new enum values and subclass ElectricCar extends Vehicle allows new types without changing existing code.
  2. Step 2: Update SpotCompatibility.COMPATIBILITY_MAP to include new compatibility rules for charging spots.

  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    New enums and subclass added, existing classes unchanged -> extensible design [check]
Hint: Add enums and subclass; update compatibility map, no existing class changes [check]
Common Mistakes:
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard