Bird
Raised Fist0

Food Ordering System

LLDmediumInterview freq: high
Choose your preparation mode4 modes available
▶
Class Trace
Step 1/3
MenuItem and CartItem composition

CartItem composes MenuItem, showing strong lifecycle ownership; CartItem cannot exist without MenuItem.

🎯 Tests understanding of composition in Java where CartItem holds a reference to MenuItem and controls its lifecycle.
public class CartItem {
    private final MenuItem menuItem;
    private int quantity;
    public CartItem(MenuItem menuItem, int quantity) {
        this.menuItem = menuItem;
        this.quantity = quantity;
    }
    public double getTotal() {
        return menuItem.getPrice() * quantity;
    }
}
Cart composition and synchronized addItem method

Cart composes multiple CartItems and uses synchronized addItem to ensure thread-safe updates to items list.

🎯 Tests knowledge of synchronized keyword in Java to prevent race conditions when multiple threads modify Cart concurrently.
public class Cart {
    private final List<CartItem> items = new ArrayList<>();
    public synchronized void addItem(CartItem item) {
        items.add(item);
    }
    public double getTotal() {
        return items.stream().mapToDouble(CartItem::getTotal).sum();
    }
}
Order composition of Cart and status management

Order composes Cart and manages order lifecycle with status enum; Cart cannot exist independently once part of Order.

🎯 Tests understanding of composition lifecycle and use of enum for order status management in Java.
public class Order {
    private final Cart cart;
    private OrderStatus status;
    public Order(Cart cart) {
        this.cart = cart;
        this.status = OrderStatus.NEW;
    }
    public void placeOrder() {
        status = OrderStatus.PLACED;
    }
    public void cancelOrder() {
        status = OrderStatus.CANCELLED;
    }
    public enum OrderStatus { NEW, PLACED, CANCELLED }
}
📐
Class Diagram
Class Diagram
       +----------------+
       |   MenuItem     |
       +----------------+
       | - id: String   |
       | - name: String |
       | - price: double|
       +----------------+
       | + getPrice():  |
       |   double       |
       +----------------+
              │
              │ composition
              ▼
       +----------------+
       |   CartItem     |
       +----------------+
       | - menuItem:    |
       |   MenuItem     |
       | - quantity: int|
       +----------------+
       | + getTotal():  |
       |   double       |
       +----------------+
              │
              │ composition
              ▼
       +----------------+
       |     Cart       |
       +----------------+
       | - items: List< |
       |   CartItem>    |
       +----------------+
       | + addItem([sync])|
       |   (CartItem)   |
       | + getTotal():  |
       |   double       |
       +----------------+
              │
              │ composition
              ▼
       +----------------+
       |     Order      |
       +----------------+
       | - cart: Cart   |
       | - status: enum |
       +----------------+
       | + placeOrder() |
       | + cancelOrder()|
       +----------------+

This class diagram illustrates key Java-specific design decisions in a Food Ordering System. MenuItem is a simple entity representing food with state, composed by CartItem which adds quantity behavior. Cart composes multiple CartItems and uses synchronized methods to ensure thread-safe modifications, preventing race conditions in concurrent environments. Order composes Cart and manages lifecycle with an enum status, enforcing strong lifecycle ownership and clear state transitions. The diagram emphasizes composition over association for lifecycle control and uses synchronized methods for concurrency, demonstrating SOLID principles and Java concurrency mechanisms.

Primary Focus

✓ Composition vs Association lifecycle + Abstract class state + Synchronized methods concurrency

Practice

(1/5)
1. In a Java codebase, a factory class provides methods to create related objects like Button and Checkbox families without specifying their concrete classes. Which design pattern is applied here and why is it the correct choice?
easy
A. Singleton pattern, because it ensures only one factory instance exists.
B. Builder pattern, because it constructs complex objects step-by-step.
C. Abstract Factory pattern, because it creates families of related objects without specifying their concrete classes.
D. Prototype pattern, because it clones existing objects to create new ones.

Solution

  1. Step 1: Identify the role of the factory class

    The factory creates multiple related objects (Button, Checkbox) without exposing their concrete classes, indicating a family of products.
  2. Step 2: Match pattern intent

    Abstract Factory pattern is designed to create families of related objects without specifying their concrete classes, unlike Builder (stepwise construction), Singleton (single instance), or Prototype (cloning).
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Abstract Factory creates related object families without concrete classes [check]
Hint: Abstract Factory creates related families, not single objects [check]
Common Mistakes:
2. In the Online Auction System, the AuctionManager class has a private constructor and a static synchronized getInstance() method. Which design pattern is applied here and why is this the correct choice?
easy
A. Singleton pattern, to ensure only one AuctionManager instance manages all auctions globally.
B. Factory pattern, because it controls object creation centrally for different auction types.
C. Builder pattern, to incrementally construct complex AuctionManager configurations.
D. Prototype pattern, to clone AuctionManager instances for each auction session.

Solution

  1. Step 1: Identify Singleton intent

    The private constructor and static synchronized getInstance() method ensure only one instance of AuctionManager exists, centralizing auction state management.
  2. Step 2: Eliminate other patterns

    Factory creates multiple objects, Builder incrementally builds complex objects, Prototype clones instances--none enforce single global instance.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Private constructor + synchronized getInstance() -> Singleton pattern [check]
Hint: Private constructor + static getInstance() -> Singleton [check]
Common Mistakes:
3. In designing a Vehicle abstraction, should it be an abstract class or an interface if it needs to hold common state like speed and fuelLevel? Why?
easy
A. Use an interface, because interfaces can hold state and provide default implementations.
B. Use an abstract class, because it can hold instance variables and provide shared behavior.
C. Use an interface, because it enforces implementation without sharing any code or state.
D. Use an abstract class, because interfaces cannot declare methods.

Solution

  1. Step 1: Analyze state and behavior requirements

    Since Vehicle needs to hold common state like speed and fuelLevel, it requires instance variables.
  2. Step 2: Choose abstraction supporting state

    Abstract classes can have instance variables and shared method implementations, whereas interfaces cannot hold instance state (only constants and default methods without state).
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    State requires instance variables -> abstract class [check]
Hint: State needs fields -> abstract class; interfaces only declare behavior [check]
Common Mistakes:
4. The current Facebook design uses a PrivacyStrategy interface for post visibility. To add a WeekendPrivacyStrategy that restricts posts only on weekends, what is the minimum change required to comply with SOLID principles?
medium
A. Modify the existing PrivacyStrategy implementations to add weekend checks.
B. Create a new WeekendPrivacyStrategy class implementing PrivacyStrategy without changing existing classes.
C. Add a boolean flag isWeekend in the base Post class and check it in all privacy methods.
D. Combine all privacy logic into a single class with conditional weekend logic.

Solution

  1. Step 1: Identify applicable SOLID principle

    Open/Closed Principle (OCP) requires extending behavior without modifying existing code.
  2. Step 2: Apply OCP to privacy strategies

    Adding a new class implementing PrivacyStrategy extends functionality without changing existing classes.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    New class for new behavior -> OCP compliance [check]
Hint: OCP: extend with new class, don't modify existing [check]
Common Mistakes:
5. To support ElectricCar and ChargingSpot in the Wallet System's parking module, what is the minimum change to the current design to maintain extensibility without modifying existing classes?
hard
A. Modify Vehicle base class to include isElectric flag and add ChargingSpot as a subclass of Spot.
B. Create a new ElectricVehicle interface and modify existing Vehicle and Spot classes to implement it.
C. Add ELECTRIC_CAR to VehicleType enum, CHARGING to SpotType enum, create ElectricCar subclass, and update SpotCompatibility map externally.
D. Add logic for ElectricCar and ChargingSpot directly inside existing Vehicle and Spot classes.

Solution

  1. Step 1: Identify extensibility without modifying existing classes

    Adding new enum values and subclasses externally allows extension without changing existing code, preserving OCP.
  2. Step 2: Use external compatibility map update

    Updating SpotCompatibility.COMPATIBILITY_MAP externally avoids modifying existing classes, enabling new vehicle and spot types to integrate cleanly.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    New enums + subclass + external map update -> no existing class changes [check]
Hint: Add enums + subclass + external map update -> no existing class change [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