Bird
Raised Fist0

Builder Pattern - Constructing Complex Objects Step by Step

LLDeasyInterview freq: common
Choose your preparation mode4 modes available
▶
Class Trace
Step 1/4
Builder abstract class

Builder is an abstract class holding a Product instance with synchronized build methods.

🎯 Tests whether candidate knows abstract class is used because Builder holds state (Product) which interfaces cannot hold in Java.
public abstract class Builder {
    protected Product product = new Product();
    public synchronized abstract void buildPartA();
    public synchronized abstract void buildPartB();
    public synchronized Product getResult() {
        return product;
    }
}
ConcreteBuilder realization

ConcreteBuilder extends Builder and overrides synchronized build methods to construct Product parts.

🎯 Tests realization relationship and synchronized overrides to ensure thread-safe incremental building of Product.
public class ConcreteBuilder extends Builder {
    @Override
    public synchronized void buildPartA() {
        product.addPart("PartA");
    }
    @Override
    public synchronized void buildPartB() {
        product.addPart("PartB");
    }
}
Director association

Director holds a reference to Builder (association) and orchestrates construction via construct() method.

🎯 Tests association relationship where Director uses Builder without owning its lifecycle, enforcing Single Responsibility Principle.
public class Director {
    private Builder builder;
    public Director(Builder builder) {
        this.builder = builder;
    }
    public void construct() {
        builder.buildPartA();
        builder.buildPartB();
    }
}
Product composition

Product is composed inside Builder, showing strong lifecycle ownership (composition).

🎯 Tests understanding of composition where Product cannot exist independently outside Builder's lifecycle.
public class Product {
    private List<String> parts = new ArrayList<>();
    public void addPart(String part) {
        parts.add(part);
    }
    public void showParts() {
        System.out.println(parts);
    }
}
📐
Class Diagram
Class Diagram
       +----------------+
       |    <<Product>> |
       |    Product     |
       +----------------+
       | - parts: List  |
       |                |
       +----------------+
       | + addPart()    |
       | + showParts()  |
       +----------------+
              ▲
              │ composition
       +----------------+
       | <<Abstract>>   |
       |    Builder     |
       +----------------+
       | - product:Prod |
       +----------------+
       | + buildPartA() [sync] |
       | + buildPartB() [sync] |
       | + getResult()  [sync] |
       +----------------+
              ▲
              │ realization
       +----------------+
       | ConcreteBuilder|
       +----------------+
       | + buildPartA() [sync] |
       | + buildPartB() [sync] |
       | + getResult()  [sync] |
       +----------------+
              ▲
              │ association
       +----------------+
       |    Director    |
       +----------------+
       | + construct()  |
       +----------------+

This Builder pattern diagram highlights key Java-specific design decisions. Builder is an abstract class because it holds mutable state (Product instance), which interfaces cannot hold in Java. ConcreteBuilder realizes Builder and overrides synchronized build methods to ensure thread-safe incremental construction. Director associates with Builder, orchestrating the build process without owning Builder's lifecycle, enforcing Single Responsibility Principle. Product is composed inside Builder, indicating strong lifecycle ownership (composition). Synchronization on build methods prevents race conditions during concurrent construction. These decisions collectively enforce Open-Closed Principle and safe concurrent usage in Java.

Primary Focus

✓ Abstract class vs Interface + Composition lifecycle + Realization + Director orchestration

Practice

(1/5)
1. In the traffic light system, the parkVehicle() method is not synchronized. Which exact sequence of Thread 1 and Thread 2 calls causes double-booking of the same parking spot?
medium
A. Thread 1 checks spot availability -> true, context switch; Thread 2 checks availability -> true; both park simultaneously
B. Thread 1 parks vehicle, Thread 2 parks vehicle after Thread 1 completes
C. Thread 1 parks vehicle, Thread 2 waits for lock and then parks
D. Thread 1 releases spot, Thread 2 parks immediately after

Solution

  1. Step 1: Identify check-then-act race condition

    Without synchronization, Thread 1 reads spot as available but before marking it occupied, context switches to Thread 2 which also reads available.
  2. Step 2: Both threads proceed to park, causing double-booking

    Both threads act on stale availability info, violating mutual exclusion.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Unsynchronized check-then-act -> double-booking race [check]
Hint: Check-then-act gap -> both see available -> double-book [check]
Common Mistakes:
2. To add a WeekendFeeStrategy for weekend bookings in the Airline Reservation System, which minimal change respects SOLID principles?
medium
A. Create a new WeekendFeeStrategy class implementing FeeStrategy and inject it without changing existing classes.
B. Add a boolean flag isWeekend to the Booking class and handle fees there.
C. Modify the existing FeeCalculator class to add weekend fee logic inside the calculate method.
D. Extend the FeeCalculator class with a subclass that overrides fee calculation for weekends.

Solution

  1. Step 1: Identify SOLID principle involved

    The Open-Closed Principle (OCP) requires that existing classes remain unchanged when adding new behavior.
  2. Step 2: Evaluate options for OCP compliance

    Add a boolean flag isWeekend to the Booking class and handle fees there. adds a flag and handles fees in Booking, violating SRP and mixing concerns. Create a new WeekendFeeStrategy class implementing FeeStrategy and inject it without changing existing classes. cleanly adds a new strategy class without modifying existing code, respecting OCP and DIP.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    New FeeStrategy class -> no existing class modification -> OCP respected [check]
Hint: New strategy class -> no existing code change -> OCP [check]
Common Mistakes:
3. In the Stack Overflow voting system, if the castVote() method is not synchronized, which exact sequence of thread interleaving causes a double vote count for the same user on a question?
medium
A. Thread 1 reads vote count, Thread 2 reads vote count, both increment and write back simultaneously
B. Thread 1 checks if user has voted -> false, context switch; Thread 2 checks if user has voted -> false; both proceed to cast vote
C. Thread 1 updates vote count, Thread 2 waits; Thread 1 finishes, Thread 2 updates vote count again
D. Thread 1 and Thread 2 both block on the same lock, causing deadlock

Solution

  1. Step 1: Identify the check-then-act race condition

    The critical issue is the check if the user has already voted. Without synchronization, both threads see no vote recorded and proceed.
  2. Step 2: Trace exact interleaving causing double vote

    Thread 1 checks voted -> false, context switch; Thread 2 checks voted -> false; both cast votes, causing double count.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Check-then-act gap without sync -> double vote [check]
Hint: Check-then-act gap -> double vote without sync [check]
Common Mistakes:
4. ElectricCar needs to be added to the product catalog with ChargingSpots. What is the minimum change to support this without modifying existing classes?
hard
A. Create a new ElectricCar class and a new ChargingSpot class, modifying Vehicle and Spot base classes to support them
B. Add ELECTRIC_CAR to VehicleType enum and CHARGING to SpotType enum, create ElectricCar extends Vehicle, update SpotCompatibility.COMPATIBILITY_MAP accordingly
C. Modify Vehicle class to add isElectric flag and add charging logic inside existing ParkingSpot classes
D. Add charging logic inside Vehicle class and extend SpotType enum with charging spots, modifying existing compatibility logic

Solution

  1. Step 1: Identify extensibility without modifying existing classes

    Adding new enum values and new classes for ElectricCar and ChargingSpot allows extension without changing existing class code, preserving OCP.
  2. Step 2: Why updating compatibility map is needed

    SpotCompatibility.COMPATIBILITY_MAP controls which vehicles fit which spots; updating it ensures ElectricCar and ChargingSpot compatibility without modifying base classes.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    New enums + classes + compatibility map update -> minimal existing class changes [check]
Hint: Add enums + classes + map, no base class changes [check]
Common Mistakes:
5. ElectricCar needs to park in ChargingSpots. What is the minimum change to the current design with VehicleType and SpotType enums, and SpotCompatibility map, to support this without modifying existing classes?
hard
A. Modify Vehicle class to include a boolean isElectric flag and add logic in ParkingLot to handle charging spots.
B. Add ELECTRIC_CAR to VehicleType, CHARGING to SpotType, create ElectricCar extending Vehicle, and update SpotCompatibility.COMPATIBILITY_MAP with new entries.
C. Create a new ElectricVehicle interface and modify all existing vehicle classes to implement it where applicable.
D. Add a ChargingSpot subclass of ParkingSpot and hardcode electric car checks in ParkingLot methods.

Solution

  1. Step 1: Identify extensibility requirements

    Adding ElectricCar and ChargingSpot requires new enum values and a new class without modifying existing classes to respect OCP.
  2. Step 2: Apply minimal change with enums and composition

    Adding new enum constants and extending Vehicle with ElectricCar allows reuse of existing logic. Updating SpotCompatibility.COMPATIBILITY_MAP with new mappings supports compatibility without changing existing code.
  3. Step 3: Eliminate options violating OCP

    Options B, C, and D modify existing classes or require widespread changes, violating OCP and risking regressions.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    New enums + subclass + compatibility map update -> minimal, OCP-compliant [check]
Hint: Add enums + subclass + map update, 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