Bird
Raised Fist0

Order Management System

LLDmediumInterview freq: high
Choose your preparation mode4 modes available
▶
Class Trace
Step 1/3
Order and composition with OrderStateHandler

Order class composes OrderStateHandler, showing ownership and lifecycle control of state handler.

🎯 Tests whether candidate understands composition lifecycle: OrderStateHandler cannot exist without Order, enforcing encapsulation and lifecycle management.
public class Order {
    private final String id;
    private final List<OrderItem> items;
    private final Customer customer;
    private OrderStateHandler stateHandler;

    public Order(String id, List<OrderItem> items, Customer customer) {
        this.id = id;
        this.items = items;
        this.customer = customer;
        this.stateHandler = new PlacedStateHandler(this);
    }
}
OrderStateHandler abstract class with shared state

OrderStateHandler is abstract class holding reference to Order and defining synchronized handleState method.

🎯 Tests whether candidate knows abstract class is used (not interface) because shared state (Order reference) and synchronized behavior are needed.
public abstract class OrderStateHandler {
    protected final Order order;

    protected OrderStateHandler(Order order) {
        this.order = order;
    }

    public synchronized abstract void handleState();
}
Concrete state handler PlacedStateHandler realization

PlacedStateHandler extends OrderStateHandler and implements handleState with synchronized keyword to ensure thread safety.

🎯 Tests whether candidate understands synchronized method prevents race conditions when multiple threads try to change order state concurrently.
public class PlacedStateHandler extends OrderStateHandler {
    public PlacedStateHandler(Order order) {
        super(order);
    }

    @Override
    public synchronized void handleState() {
        // Transition logic from Placed to Confirmed
        order.setStateHandler(new ConfirmedStateHandler(order));
    }
}
📐
Class Diagram
Class Diagram
       +----------------------+
       |       Order          |
       |----------------------|
       | - id: String          |
       | - items: List<OrderItem>|
       | - customer: Customer   |
       | - stateHandler: OrderStateHandler |
       |----------------------|
       | + placeOrder(): void  |
       | + cancelOrder(): void |
       | + advanceState(): void|
       +----------------------+
               ◆ composition
               │
               │
       +-----------------------------+
       | <<Abstract>> OrderStateHandler|
       |-----------------------------|
       | - order: Order               |
       |-----------------------------|
       | + handleState(): void [sync]|
       +-----------------------------+
               │ extends
               │
       +-----------------------------+
       | PlacedStateHandler           |
       |-----------------------------|
       | + handleState(): void [sync] |
       +-----------------------------+
               │ extends
               │
       +-----------------------------+
       | ConfirmedStateHandler        |
       |-----------------------------|
       | + handleState(): void [sync] |
       +-----------------------------+

This class diagram illustrates the Order Management System's state pattern implementation using an abstract class OrderStateHandler to hold shared state and synchronized behavior. The Order class composes OrderStateHandler, enforcing lifecycle ownership and encapsulation. Concrete state handlers like PlacedStateHandler extend the abstract class and override synchronized methods to safely transition order states. This design leverages Java-specific features: abstract classes for shared state and synchronized methods for thread safety, fulfilling the Open-Closed Principle by allowing new states without modifying existing code. The composition relationship ensures OrderStateHandler's lifecycle is bound to Order, preventing dangling state handlers.

Primary Focus

✓ Abstract class vs Interface for state + Composition lifecycle + State pattern realization

Practice

(1/5)
1. In an LRU Cache implemented with a HashMap and Doubly Linked List, which design pattern best describes the role of the Doubly Linked List in maintaining cache order?
easy
A. Iterator pattern, because it maintains the order of elements for quick traversal and eviction.
B. Decorator pattern, as it adds caching behavior to the HashMap without modifying it.
C. Composite pattern, since the list nodes form a tree-like structure representing cache entries.
D. Factory pattern, because it creates nodes dynamically when cache entries are added.

Solution

  1. Step 1: Identify the role of the Doubly Linked List

    The Doubly Linked List maintains the order of cache entries from most recently used to least recently used, enabling quick eviction of the least recently used item.
  2. Step 2: Match the pattern to this role

    The Iterator pattern fits because it provides ordered traversal over the cache entries, allowing the system to efficiently move nodes and evict the least recently used.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Doubly Linked List enables ordered traversal and eviction [check]
Hint: Doubly Linked List enables ordered traversal [check]
Common Mistakes:
2. In the Stack Overflow design, the Vote class has a private constructor and a static synchronized getInstance() method. Which design pattern is applied here and why is this the correct use case?
easy
A. Factory pattern, because it controls object creation with parameters
B. Prototype pattern, to clone existing Vote instances for performance
C. Singleton pattern, to ensure only one Vote manager instance handles voting logic
D. Builder pattern, to incrementally construct Vote objects with complex state

Solution

  1. Step 1: Identify the pattern from constructor and method

    The private constructor prevents external instantiation, and the static synchronized getInstance() method ensures a single instance is created and accessed thread-safely.
  2. Step 2: Why Singleton fits Vote manager

    Vote management requires a single point of control to maintain consistent vote counts and prevent conflicting updates, which Singleton enforces.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Private constructor + synchronized static getInstance() -> Singleton [check]
Hint: Private constructor + static synchronized getInstance() -> Singleton [check]
Common Mistakes:
3. You want to add a WeekendFeeStrategy to calculate parking fees differently on weekends using the current adapter-based design. What is the minimum change required to comply with SOLID principles?
medium
A. Add a boolean flag to Vehicle to indicate weekend and modify ParkingLot to check it.
B. Create a new WeekendFeeStrategy class implementing FeeStrategy and inject it where needed without modifying existing classes.
C. Modify the existing FeeStrategy class to add weekend logic with if-else checks.
D. Add weekend fee logic inside the adapter class that adapts Vehicle to ParkingLot.

Solution

  1. Step 1: Identify SOLID principle involved

    Open-Closed Principle (OCP) requires extending behavior without modifying existing code.
  2. Step 2: Evaluate options

    Create a new WeekendFeeStrategy class implementing FeeStrategy and inject it where needed without modifying existing classes. respects OCP by adding a new class implementing FeeStrategy. Add a boolean flag to Vehicle to indicate weekend and modify ParkingLot to check it. modifies Vehicle and ParkingLot, violating OCP. Options A and D modify existing classes.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    New strategy class extends behavior without modifying existing code [check]
Hint: OCP: extend with new class, don't modify existing ones [check]
Common Mistakes:
4. The ATM system currently calculates transaction fees using a FeeCalculator class. To add a WeekendFeeStrategy without modifying existing classes, which SOLID principle applies and what is the minimal correct change?
medium
A. Add a boolean flag isWeekend in FeeCalculator and branch logic accordingly, maintaining SRP.
B. Modify FeeCalculator to add weekend logic, violating OCP but keeping code simple.
C. Create WeekendFeeStrategy implementing FeeStrategy interface; FeeCalculator uses FeeStrategy via dependency injection, adhering to OCP and DIP.
D. Create WeekendFeeStrategy subclassing FeeCalculator and override fee calculation, violating DIP.

Solution

  1. Step 1: Identify applicable SOLID principles

    Open-Closed Principle (OCP) requires FeeCalculator not be modified for new fee types. Dependency Inversion Principle (DIP) requires FeeCalculator depend on abstractions.
  2. Step 2: Apply correct design

    Create WeekendFeeStrategy implementing FeeStrategy interface. Inject FeeStrategy into FeeCalculator. This adds new behavior without modifying existing code.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    New strategy class + DI -> OCP and DIP respected [check]
Hint: New fee? Add strategy class, inject via interface [check]
Common Mistakes:
5. You need to add support for ElectricCar and ChargingSpot in the existing parking system using Decorator pattern. What is the minimum change to support this without modifying existing classes and avoiding class explosion?
hard
A. Add ELECTRIC_CAR to VehicleType, CHARGING to SpotType, create ElectricCar extending Vehicle, and update SpotCompatibility.COMPATIBILITY_MAP accordingly.
B. Modify Vehicle and Spot classes to include electric-specific fields and logic.
C. Create separate parallel class hierarchy for electric vehicles and spots, duplicating existing logic.
D. Add boolean isElectric flag to Vehicle and Spot and handle logic with conditionals.

Solution

  1. Step 1: Identify extensibility requirements

    Adding ElectricCar and ChargingSpot should not modify existing classes to respect OCP and avoid class explosion.
  2. Step 2: Evaluate options for minimal change

    Add ELECTRIC_CAR to VehicleType, CHARGING to SpotType, create ElectricCar extending Vehicle, and update SpotCompatibility.COMPATIBILITY_MAP accordingly. adds new enum values and a subclass, updating compatibility map without changing existing classes, adhering to OCP. Modify Vehicle and Spot classes to include electric-specific fields and logic. modifies existing classes, violating OCP. Create separate parallel class hierarchy for electric vehicles and spots, duplicating existing logic. duplicates logic, causing class explosion. Add boolean isElectric flag to Vehicle and Spot and handle logic with conditionals. adds flags and conditionals, increasing complexity and violating SRP.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    New enums and subclass added; existing classes unchanged [check]
Hint: Add enums and subclass; avoid modifying existing classes [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