Proxy
Substitutes another object to control access to it (lazy load, security, caching, remoting).
Context
You want to add cross-cutting concerns (authorization, lazy loading, logging, caching) without the client knowing.
Problem
Modifying the real object introduces concerns that are not its own.
Solution
A Proxy implements the same interface and delegates, adding control before/after the call.
#Example in C# — Virtual Proxy (lazy)
public interface IImage { void Display(); }
public class HighResImage : IImage
{
private readonly string _path;
public HighResImage(string path) { _path = path; /* loads 5 MB */ }
public void Display() => Console.WriteLine(quot;Displaying {_path}");
}
public class ImageProxy : IImage
{
private readonly string _path;
private HighResImage? _real;
public ImageProxy(string path) => _path = path;
public void Display()
{
_real ??= new HighResImage(_path); // loads only the first time
_real.Display();
}
}When NOT to use it
- When the actual cost is already low.
- When the control could live in the caller (decorator/middleware).
Tradeoffs
| Pro | Con |
|---|---|
| Transparent control to client | One more layer of indirection |
| Fits with AOP / interceptors | Can hide unexpected latency |
#Variants
- Virtual Proxy (lazy load).
- Protection Proxy (authorization).
- Remote Proxy (represents objects in another process/machine).
- Smart Reference (counts references, releases).
#structural #gof #wrapper