What is the Proxy pattern?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
Answer
The Proxy pattern provides a surrogate or placeholder for another object to control access to it. Types: Virtual Proxy (lazy initialization), Protection Proxy (access control), Remote Proxy (remote object), Logging Proxy, Caching Proxy. Caching proxy example: interface ImageLoader { BufferedImage loadImage(String url); } class RealImageLoader implements ImageLoader { @Override public BufferedImage loadImage(String url) { System.out.println("Loading from network: " + url); return downloadFromNetwork(url); // Slow! } } class CachingImageProxy implements ImageLoader { private Map<String, BufferedImage> cache = new HashMap<>(); private ImageLoader realLoader = new RealImageLoader(); @Override public BufferedImage loadImage(String url) { if (cache.containsKey(url)) { System.out.println("Cache hit: " + url); return cache.get(url); } System.out.println("Cache miss, loading: " + url); BufferedImage image = realLoader.loadImage(url); cache.put(url, image); return image; } }. Protection proxy (access control): class SecureDocumentProxy implements Document { private Document realDocument; private User currentUser; @Override public String getContent() { if (!currentUser.hasPermission("READ")) { throw new SecurityException("Access denied"); } return realDocument.getContent(); } @Override public void setContent(String content) { if (!currentUser.hasPermission("WRITE")) { throw new SecurityException("Access denied"); } realDocument.setContent(content); } }. Virtual proxy (lazy init): class LazyInitProxy implements HeavyService { private HeavyService instance = null; @Override public void doWork() { if (instance == null) { instance = new ExpensiveHeavyService(); // Create only when needed } instance.doWork(); } }. Real examples: Java dynamic proxies, Spring AOP proxies (for @Transactional, @Cacheable), Hibernate lazy loading proxies for entities.
Common Mistake
Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong OOP Concepts candidates.