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:

  1. 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();
    }
    
  2. 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");
        }
    }
    
  3. 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();
        }
    }
    
  4. 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:

  • ISubject is the interface that declares the common operations that both the RealSubject and Proxy must support.
  • RealSubject is the actual object that does the real work and implements the ISubject interface.
  • Proxy is a class that implements the ISubject interface as well. It maintains a reference to a RealSubject object and controls access to it. It may perform additional operations before or after forwarding the request to the real object.
  • The Client interacts 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