Explain the Proxy pattern and its common variants.
Topic: design-patterns, Structural Patterns. Level: Intermediate.
Answer
Proxy provides a **surrogate** for another object to control access to it, implementing the same interface. Variants: **Virtual** (lazy-load an expensive object on first use), **Protection** (access control/authorization), **Remote** (represent an object in another address space — RPC stubs), and **Caching/Logging** (add cross-cutting behavior). Unlike Decorator (adds behavior), Proxy primarily controls access. Spring AOP proxies are a real-world example.
```java
interface Image { void display(); }
class RealImage implements Image { // expensive to create
RealImage(String f){ loadFromDisk(f); }
public void display(){ /* show */ }
private void loadFromDisk(String f){ /* heavy */ }
}
class ImageProxy implements Image { // virtual proxy: lazy load
private final String file; private RealImage real;
ImageProxy(String f){ file = f; }
public void display() {
if (real == null) real = new RealImage(file); // created only on first use
real.display();
}
}
Image img = new ImageProxy("big.png"); // no disk load until display() is called
```