The Proxy pattern is intended to provide you with a simple placeholder that takes the place of a more complex object that may be invoked later. It is a kind of "wrapper" that delegates to the real object.
The Proxy pattern is especially useful for situations where object creation is a time consuming process, and you do not want to instantiate such an object unless and until it is actually requested by the client. This is also known as the "lazy loading" principle.
Code examples (click to enlarge/collapse):
-
12345678910111213141516171819202122232425262728293031323334353637class Program{static void Main(string[] args){Proxy proxy = new Proxy();proxy.Request(); Console.ReadKey();}}public class Proxy : Subject{private RealSubject m_RealSubject;public override void Request(){Console.WriteLine("I am proxy doing a 'lazy load'");if (m_RealSubject == null){m_RealSubject = new RealSubject();}m_RealSubject.Request();}}public abstract class Subject{public abstract void Request();}public class RealSubject : Subject{public override void Request(){Console.WriteLine(".. and I am the real subject.");}}
-
12345678910111213141516171819202122232425262728293031323334353637383940414243444546using System;class Program{static void Main(string[] args){Employee employee = new Employee(); Console.WriteLine("Employee name: {0}", employee.EmployeeName);Console.WriteLine("Manager name : {0}", employee.Manager.ManagerName); Console.WriteLine("Loading manager..");employee.Manager.Load();Console.WriteLine("Manager name: {0}", employee.Manager.ManagerName);Console.ReadKey();}}public class Employee{public string EmployeeName = "Employee";public Manager Manager = new Manager();}public class Manager : ManagerBase{private RealManager m_RealSubject;public override void Load(){if (m_RealSubject == null){m_RealSubject = new RealManager();}m_RealSubject.Load();ManagerName = m_RealSubject.ManagerName;}}public abstract class ManagerBase{public string ManagerName = "Unknown";public abstract void Load();}public class RealManager : ManagerBase{public override void Load(){ManagerName = "Manager";}}
In the simplified real world example you have two related entities Employee and Manager. Imagine both entities should be retrieved from the database. Image also that the manager has a manager, which has a manager, which has a … Before you know it, you have retreived the whole company from the database. That is not what you want, you only want to access some of the attributes of the employee and not the manager. If you want to access the employee’s manager, you have to load it explicitly.
This post is part of my series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern and look at simplified real-world C# code that implements the pattern.