Bird
Raised Fist0

Proxy Pattern - Access Control, Lazy Loading, Caching Proxy

LLDeasyInterview freq: medium
Choose your preparation mode4 modes available
▶
Class Trace
Step 1/4
Subject interface

Subject defines the common interface with request() method that RealSubject and Proxy implement.

🎯 Tests whether candidate understands interface use for OCP and that Subject cannot hold state in Java.
public interface Subject {
    void request();
}
Proxy abstract class

Proxy holds volatile RealSubject reference and CacheManager instance, implementing lazy loading and caching.

🎯 Tests why Proxy is abstract class (holds state like volatile realSubject) and uses volatile for safe lazy init.
public abstract class Proxy implements Subject {
    protected volatile RealSubject realSubject;
    protected CacheManager cacheManager;
    public synchronized void request() {
        if (realSubject == null) {
            realSubject = new RealSubject();
        }
        // caching logic here
        realSubject.request();
    }
}
Client association with Proxy

Client holds a reference to Proxy and calls execute() which delegates to Proxy.request().

🎯 Tests understanding of association lifecycle: Client depends on Proxy but Proxy can exist independently.
public class Client {
    private Proxy proxy;
    public Client(Proxy proxy) {
        this.proxy = proxy;
    }
    public void execute() {
        proxy.request();
    }
}
CacheManager composition in Proxy

Proxy composes CacheManager to handle caching; CacheManager lifecycle is bound to Proxy.

🎯 Tests composition relationship and single responsibility principle by separating caching logic into CacheManager.
public class CacheManager {
    private Map<String, Object> cache = new HashMap<>();
    public Object get(String key) {
        return cache.get(key);
    }
    public void put(String key, Object value) {
        cache.put(key, value);
    }
}
📐
Class Diagram
Class Diagram
       +----------------+
       | <<Interface>>  |
       |    Subject     |
       +----------------+
       | +request():void|
       +----------------+
              ▲
              │ ─ ─ ─► RealSubject
              │
       +----------------+
       | <<Abstract>>   |
       |     Proxy      |
       +----------------+
       | -realSubject:  |
       |   volatile RealSubject |
       | -cacheManager: |
       |   CacheManager |
       +----------------+
       | +request():void [sync] |
       +----------------+
              ▲
              │
       +----------------+
       |    Client      |
       +----------------+
       | -proxy: Proxy  |
       +----------------+
       | +execute():void|
       +----------------+
              │
              │ ──► CacheManager
       +----------------+
       | CacheManager   |
       +----------------+
       | -cache: Map    |
       +----------------+
       | +get(key):Object|
       | +put(key, val):void|
       +----------------+

This class diagram illustrates the Proxy pattern with access control, lazy loading, and caching in Java. The Subject interface defines the contract without state, enforcing Interface Segregation. Proxy is an abstract class holding volatile RealSubject for thread-safe lazy initialization, demonstrating why abstract class beats interface here due to state. Client associates with Proxy, showing dependency without ownership, an Association relationship. Proxy composes CacheManager, encapsulating caching logic and enforcing single responsibility and lifecycle ownership. The use of volatile ensures safe publication of RealSubject instance across threads, preventing partially constructed objects. Synchronization on Proxy.request() ensures atomic check-and-set of realSubject, avoiding race conditions. This design cleanly separates concerns and follows SOLID principles, enabling extensibility without modifying existing classes.

Primary Focus

✓ Abstract class vs Interface + Composition lifecycle + Lazy Initialization volatile + Caching responsibility

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 Online Shopping Cart system, the Cart 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 centrally.
B. Singleton pattern, to ensure only one Cart instance exists per user session.
C. Builder pattern, to construct Cart objects step-by-step.
D. Prototype pattern, to clone Cart instances efficiently.

Solution

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

    The private constructor prevents external instantiation, and the static synchronized getInstance() method controls instance creation, which matches the Singleton pattern.
  2. Step 2: Reason why Singleton fits Cart

    Ensuring only one Cart instance per user session avoids inconsistent states and duplicate carts, which is the intended use case here.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Private constructor + synchronized getInstance() -> Singleton pattern [check]
Hint: Private constructor + static getInstance() -> Singleton [check]
Common Mistakes:
3. You want to add a WeekendBonusRule that gives players extra moves on weekends without modifying existing classes. Which SOLID principle guides the minimal change, and what is the correct approach?
medium
A. Single Responsibility Principle: add weekend logic inside the Player class.
B. Open/Closed Principle: create a new class implementing a MoveRule interface and inject it into the game engine.
C. Liskov Substitution Principle: subclass Player to WeekendPlayer with bonus logic.
D. Dependency Inversion Principle: make Player depend on concrete WeekendBonusRule.

Solution

  1. Step 1: Identify SOLID principle for extension without modification

    Open/Closed Principle (OCP) states software entities should be open for extension but closed for modification.
  2. Step 2: Evaluate approaches

    Subclassing Player to WeekendPlayer allows extension without modifying Player; injecting new MoveRule class also respects OCP but requires interface design.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Subclassing extends behavior without modifying base class [check]
Hint: Extend via subclass or interface, don't modify existing classes [check]
Common Mistakes:
4. ElectricCar pieces require special ChargingSpot compatibility in the Jigsaw Puzzle System. What is the minimum design change to support ElectricCar and ChargingSpot without modifying existing classes?
hard
A. Add ELECTRIC_CAR to PieceType enum, CHARGING to SpotType enum, create ElectricCarPiece subclass, and update compatibility map externally.
B. Modify existing Piece and Spot classes to include electric-specific fields and logic.
C. Create a new ElectricCarPiece class implementing a new interface and modify Board to handle it specially.
D. Add a god-class CompatibilityManager that hardcodes all compatibility rules including electric cars.

Solution

  1. Step 1: Identify extensibility requirements

    New piece and spot types must be added without modifying existing classes to respect OCP.
  2. Step 2: Evaluate minimal change approach

    Adding new enum values and subclass for ElectricCarPiece plus updating compatibility map externally allows extension without modifying existing code.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    New enums and subclass extend system without changing existing classes [check]
Hint: Add enums + subclass + external map update = minimal invasive extension [check]
Common Mistakes:
5. To add ElectricCar and ChargingSpot support without modifying existing classes, what is the minimum change to the current Java design?
hard
A. Create a new ElectricCar class with charging logic inside Vehicle, and add ChargingSpot as a subclass of Spot with overrides.
B. Modify Vehicle and Spot classes to add electric-specific fields and methods, then create ElectricCar and ChargingSpot subclasses.
C. Add electric vehicle logic inside existing Vehicle class and charging spot logic inside Spot class, avoiding new enums.
D. Add ELECTRIC_CAR to VehicleType enum, CHARGING to SpotType enum, create ElectricCar subclass, and update SpotCompatibility.COMPATIBILITY_MAP; no existing classes modified.

Solution

  1. Step 1: Identify extensibility without modifying existing classes

    Adding new enum values and new subclasses allows extension without changing existing class code, respecting OCP.
  2. Step 2: Use compatibility map update for new spot-vehicle matching

    Updating SpotCompatibility.COMPATIBILITY_MAP with new types supports new logic without modifying existing classes' internals.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    New enums + subclasses + compatibility map update -> minimal change, no existing class modification [check]
Hint: Add enums + subclasses + compatibility map -> extend without modify [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