Bird
Raised Fist0

Library Management System

LLDmediumInterview freq: medium
Choose your preparation mode4 modes available
▶
Class Trace
Step 1/4
LibraryCatalog Singleton

LibraryCatalog uses a private volatile static instance and a synchronized getInstance() method to ensure thread-safe lazy initialization.

🎯 Tests whether candidate knows volatile prevents instruction reordering allowing safe publication of the singleton instance in Java.
public class LibraryCatalog {
    private static volatile LibraryCatalog instance;
    private LibraryCatalog() { }
    public static synchronized LibraryCatalog getInstance() {
        if (instance == null) {
            instance = new LibraryCatalog();
        }
        return instance;
    }
}
Composition between LibraryCatalog and Book

LibraryCatalog has a composition relationship with Book copies, owning their lifecycle and managing them internally.

🎯 Tests understanding of composition in Java where LibraryCatalog controls BookCopy lifecycle, enforcing encapsulation and single responsibility.
public class LibraryCatalog {
    private Map<Book, List<BookCopy>> books = new HashMap<>();
    public synchronized void addBookCopy(BookCopy copy) {
        books.computeIfAbsent(copy.getBook(), k -> new ArrayList<>()).add(copy);
    }
}
Association between Book and BookCopy

BookCopy holds a reference to Book but has an independent lifecycle, modeled as association, not composition.

🎯 Tests whether candidate distinguishes association from composition based on lifecycle ownership in Java.
public class BookCopy {
    private Book book;
    private String copyId;
    private volatile boolean isAvailable;
    public BookCopy(Book book, String copyId) {
        this.book = book;
        this.copyId = copyId;
        this.isAvailable = true;
    }
    public boolean isAvailable() { return isAvailable; }
    public void setAvailable(boolean available) { this.isAvailable = available; }
    public Book getBook() { return book; }
}
FinePolicy Interface Realization

FinePolicy defines a method to calculate fines, allowing multiple implementations to realize this interface for extensibility.

🎯 Tests understanding of interface usage in Java to enforce Open-Closed Principle by allowing new fine policies without modifying existing code.
public interface FinePolicy {
    double calculateFine(int daysLate);
}
public class DefaultFinePolicy implements FinePolicy {
    public double calculateFine(int daysLate) {
        return daysLate * 1.0; // flat rate
    }
}
📐
Class Diagram
Class Diagram
       +----------------+
       | <<Singleton>>  |
       | LibraryCatalog |
       +----------------+
       | -instance: vol. LibraryCatalog
       | -books: Map<Book, List<BookCopy>>
       +----------------+
       | +getInstance(): LibraryCatalog [sync]
       | +addBookCopy(BookCopy): void
       +----------------+
              │ composition
              │
       +----------------+
       |     Book       |
       +----------------+
       | -isbn: String  |
       | -title: String |
       +----------------+
       | +getIsbn(): String
       | +getTitle(): String
       +----------------+
              │ association
              │
       +----------------+
       |   BookCopy     |
       +----------------+
       | -copyId: String|
       | -isAvailable: boolean
       +----------------+
       | +isAvailable(): boolean
       | +setAvailable(boolean): void
       +----------------+
              │ association
              │
       +----------------+
       |    Member      |
       +----------------+
       | -memberId: String
       | -name: String  |
       +----------------+
       | +getMemberId(): String
       | +getName(): String
       +----------------+
              │ association
              │
       +----------------+
       |  FinePolicy    |
       +----------------+
       | +calculateFine(daysLate: int): double
       +----------------+

This diagram illustrates key Java-specific design decisions in a Library Management System. LibraryCatalog is a Singleton with a volatile instance and synchronized getInstance() method to ensure thread-safe lazy initialization, preventing instruction reordering issues. It composes BookCopy objects, owning their lifecycle, enforcing encapsulation and adhering to the Single Responsibility Principle. BookCopy associates with Book, reflecting independent lifecycles, demonstrating association versus composition. FinePolicy is an interface realized by concrete classes, enabling Open-Closed Principle compliance by allowing new fine calculation strategies without modifying existing code. These decisions highlight Java concurrency mechanisms, lifecycle ownership, and extensibility patterns critical for robust LLD.

Primary Focus

✓ Singleton volatile + Composition vs Association lifecycle + Interface realization

Practice

(1/5)
1. In designing the Vehicle abstraction for the Ride Booking system, should Vehicle be an abstract class or an interface, and why?
easy
A. Abstract class, because Vehicle has common state like licensePlate and shared methods like startEngine().
B. Interface, because Vehicle only defines behavior without any shared state or implementation.
C. Interface, because Java interfaces can now have default methods to share code and state.
D. Abstract class, because interfaces cannot enforce method signatures.

Solution

  1. Step 1: Analyze Vehicle's shared state and behavior

    Vehicle has common fields (e.g., licensePlate) and methods (e.g., startEngine) that require shared implementation and state storage.
  2. Step 2: Abstract class vs interface suitability

    Abstract classes allow shared state and method implementations, while interfaces cannot hold instance state. Thus, abstract class fits Vehicle better.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Shared state + behavior -> abstract class [check]
Hint: Shared state means abstract class, not interface [check]
Common Mistakes:
2. The Jigsaw Puzzle System currently calculates fit scores using a FitStrategy interface. To add a WeekendFitBonus that modifies scoring only on weekends, which minimal change respects SOLID principles?
medium
A. Modify existing FitStrategy implementations to add weekend logic inside their calculateFit() methods.
B. Create a new WeekendFitStrategyDecorator that wraps existing strategies and adds weekend bonus, without modifying existing classes.
C. Add weekend logic directly inside the Board class before calling fit calculations.
D. Add a boolean isWeekend flag to the Board class and pass it to all fit calculations.

Solution

  1. Step 1: Identify SOLID principle involved

    Open-Closed Principle (OCP) requires adding new behavior without modifying existing classes.
  2. Step 2: Evaluate options for minimal change respecting OCP

    Add a boolean isWeekend flag to the Board class and pass it to all fit calculations. adds a weekend flag to Board and passes it, allowing existing strategies to remain unchanged but adapt behavior based on context.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Passing context flag avoids modifying existing FitStrategy classes [check]
Hint: OCP: add behavior via context, not modifying existing classes [check]
Common Mistakes:
3. You want to add a WeekendRetryPolicy to the Job Scheduler without modifying existing classes. Which SOLID principle guides the minimum change, and what is the correct approach?
medium
A. Open/Closed Principle: create a new class WeekendRetryPolicy implementing RetryPolicy interface without changing existing code.
B. Single Responsibility Principle: modify RetryPolicy to handle weekends explicitly.
C. Dependency Inversion Principle: inject WeekendRetryPolicy into Job class by modifying Job constructor.
D. Liskov Substitution Principle: override existing RetryPolicy methods to add weekend logic.

Solution

  1. Step 1: Identify the SOLID principle for extensibility

    Open/Closed Principle (OCP) states software entities should be open for extension but closed for modification.
  2. Step 2: Apply OCP to add WeekendRetryPolicy

    Create a new class implementing RetryPolicy interface to add weekend-specific logic without modifying existing RetryPolicy or Job classes.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    New class implements interface -> no existing code changed [check]
Hint: OCP: extend by new class, don't modify existing [check]
Common Mistakes:
4. The Airline Reservation System needs to support ElectricCar vehicles requiring ChargingSpot parking. What is the minimum change to the current Java design to support this without modifying existing classes?
hard
A. Add ELECTRIC_CAR to VehicleType enum, CHARGING to SpotType enum, create ElectricCar subclass, and update SpotCompatibility map externally.
B. Modify Vehicle base class to include charging capability and add ChargingSpot as a new subclass of Spot.
C. Create a new Vehicle hierarchy for electric cars and a separate ParkingLot for charging spots.
D. Add a boolean isElectric field to Vehicle and conditionally handle charging spots in existing Spot classes.

Solution

  1. Step 1: Identify extensibility requirements

    Adding ElectricCar and ChargingSpot must not modify existing classes to respect OCP and avoid class explosion.
  2. Step 2: Minimal change approach

    Adding new enum values and creating new subclasses for ElectricCar and ChargingSpot, plus updating compatibility externally, extends functionality without changing existing code.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    New enums + subclasses + external compatibility update -> no existing class change [check]
Hint: New enums + subclasses + external map -> no existing class edits [check]
Common Mistakes:
5. ElectricCar requires ChargingSpots in the parking system using Prototype pattern. What is the minimum change to support this without modifying existing classes?
hard
A. Modify Vehicle base class to include charging logic and add ChargingSpot as a subclass of Spot
B. Add charging logic inside Vehicle clone() and modify SpotCompatibility map inside existing classes
C. Add ELECTRIC_CAR to VehicleType enum, CHARGING to SpotType enum, create ElectricCar subclass, and update SpotCompatibility map externally
D. Create a god-class that handles both ElectricCar and ChargingSpot logic to avoid modifying existing classes

Solution

  1. Step 1: Identify extensibility requirements

    Adding ElectricCar and ChargingSpot must avoid modifying existing classes to respect OCP.
  2. Step 2: Evaluate options for minimal invasive change

    Add ELECTRIC_CAR to VehicleType enum, CHARGING to SpotType enum, create ElectricCar subclass, and update SpotCompatibility map externally adds new enum values and subclasses externally, updating compatibility map without changing existing code. Options B and C modify base classes, violating OCP. Create a god-class that handles both ElectricCar and ChargingSpot logic to avoid modifying existing classes creates god-class, violating SRP and maintainability.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    New enums + subclass + external map update -> minimal change, OCP respected [check]
Hint: New enums + subclass + external map -> minimal invasive 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