Saturday, February 12, 2011

The proxy Pattern

Proxy Design pattern

Proxy pattern is one of the commonly used structural design pattern. A proxy, in its most general form, is a class functioning as an interface to something else. Proxy instantiates the real object the first time the client makes a request of the proxy, who  remembers the identity of this real object, and forwards the instigating request to this real object. Then all subsequent requests are simply forwarded directly to the encapsulated real object

There are four common situations in which the Proxy pattern is applicable.
  1. A virtual proxy is a placeholder for “expensive to create” objects. The real object is only created when a client first requests/accesses the object.
  2. A remote proxy provides a local representative for an object that resides in a different address space. This is what the “stub” code in RPC and CORBA provides.
  3. A protective proxy controls access to a sensitive master object. The “surrogate” object checks that the caller has the access permissions required prior to forwarding the request.
  4. A smart proxy interposes additional actions when an object is accessed. Typical uses include:
    • Counting the number of references to the real object so that it can be freed automatically when there are no more references (aka smart pointer),
    • Loading a persistent object into memory when it’s first referenced,
    • Checking that the real object is locked before it is accessed to ensure that no other object can change it.

C# Code Sample

class ProxyDemo
  {
    static void Main()
    {
      // Create proxy and request a service
      Proxy proxy = new Proxy();
      proxy.Request();
      // Wait for user
      Console.Read();
    }
  }
  // "Subject"
  abstract class proxySubject
  {
    public abstract void Request();   
  }
  // "RealSubject"
  class RealSubject : proxySubject
  {
    public override void Request()
    {
      Console.WriteLine("Called RealSubject.Request()");
    }
  }
  // "Proxy"
  class Proxy : proxySubject
  {
    RealSubject realSubject;
    public override void Request()
    {
      // Use 'lazy initialization'
      if (realSubject == null)
      {
        realSubject = new RealSubject();
      }
      realSubject.Request();
    } 
  }

1 comment:

  1. Great Explanation. Another great article i recommend is this one

    dharmendra

    http://thecafetechno.com/

    ReplyDelete