Proxy Pattern: Access Control and Performance
Proxy Pattern: Access Control and Performance
The Proxy Pattern is a structural design pattern that lets you provide a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object.
ποΈ The Problem
Imagine you have an Image Viewer Application that loads high-resolution images. Loading these images from a server is a slow, memory-intensive operation. You donβt want to load all images when the app starts. You only want to load an image when itβs actually displayed on the screen.
π The .NET Implementation
The Proxy pattern is perfect for Lazy Loading, Caching, and Access Control.
1. The Common Interface
public interface IImage
{
void Display();
}2. The Real Object (Heavy and Slow)
public class RealImage : IImage
{
private readonly string _filename;
public RealImage(string filename)
{
_filename = filename;
LoadFromDisk();
}
private void LoadFromDisk() => Console.WriteLine($"[IO]: Loading heavy image: {_filename}");
public void Display() => Console.WriteLine($"[DISPLAY]: Rendering {_filename}");
}3. The Proxy (Lightweight Placeholder)
public class ProxyImage : IImage
{
private readonly string _filename;
private RealImage _realImage; // Only loaded when needed!
public ProxyImage(string filename) => _filename = filename;
public void Display()
{
// π LAZY INITIALIZATION: Load the real image only on demand!
if (_realImage == null)
{
_realImage = new RealImage(_filename);
}
_realImage.Display();
}
}π οΈ Real-World Usage (Client)
// Use the Proxy instead of the Real object
IImage image = new ProxyImage("high_res_photo.png");
// 1. First time call: Real object IS created and then displayed
image.Display();
// 2. Second time call: Real object is ALREADY created, just displayed
image.Display();π‘ Why use Proxy?
- Lazy Loading (Virtual Proxy): Delay the creation of heavy objects until they are absolutely needed.
- Access Control (Protection Proxy): Only allow specific users to call the real object.
- Caching: Store the results of expensive operations in the proxy.
- Logging/Monitoring: Perform logging before and after calling the real object (similar to the Decorator, but the Proxy manages the lifecycle of the real object).