04 Dec 2023
Advanced
The Proxy design pattern is a structural pattern that provides a surrogate or placeholder for another object to control access to it. In C#, the Proxy pattern typically involves the following main components:
-
Subject Interface:
- Declares the common interface for both RealSubject and Proxy so that the Proxy can be used wherever a RealSubject is expected.
public interface ISubject { void Request(); } -
RealSubject:
- Implements the Subject interface.
- Defines the real object that the Proxy represents.
public class RealSubject : ISubject { public void Request() { Console.WriteLine("RealSubject: Handling Request"); } } -
Proxy:
- Implements the Subject interface.
- Maintains a reference to the RealSubject.
- Controls access to the RealSubject, possibly by performing some additional operations before or after forwarding the request.
public class Proxy : ISubject { private RealSubject realSubject; public void Request() { // Check some conditions, perform additional operations, etc. if (realSubject == null) { realSubject = new RealSubject(); } // Forward the request to the real object realSubject.Request(); } } -
Client:
- Interacts with the Proxy or RealSubject through the common interface (Subject).
class Client { static void Main() { // Using the Proxy ISubject proxy = new Proxy(); proxy.Request(); } }
In this example:
ISubjectis the interface that declares the common operations that both the RealSubject and Proxy must support.RealSubjectis the actual object that does the real work and implements theISubjectinterface.Proxyis a class that implements theISubjectinterface as well. It maintains a reference to aRealSubjectobject and controls access to it. It may perform additional operations before or after forwarding the request to the real object.- The
Clientinteracts with the Proxy through the common interface, without being aware of whether it is dealing with the Proxy or the RealSubject.
The Proxy pattern is useful in scenarios where you want to add some level of control over the access to the real object. This control can involve lazy initialization, access control, logging, or other behaviors without changing the interface of the RealSubject.
software-design-patterns
proxy-design-pattern