13 April 2014

Proxy Design pattern -- Design Pattern

    Provide a surrogate or placeholder for another object to control access to it.

Participants

    The classes and/or objects participating in this pattern are:
  • Proxy(Math Proxy)
     Maintains a reference that lets the proxy access the real subject. Proxy may refer to a Subject if the Real Subject and Subject interfaces are the same. 

    Provides an interface identical to Subject's so that a proxy can be substituted for for the real subject.

    Controls access to the real subject and may be responsible for creating and deleting it.
other responsibilities depend on the kind of proxy:

     Remote proxies are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.

    Virtual proxies may cache additional information about the real subject so that they can postpone accessing it. For example, the Image Proxy from the Motivation caches the real images's extent.

  Protection proxies check that the caller has the access permissions required to perform a request.
  • Subject(IMath)
    Defines the common interface for Real Subject and Proxy so that a Proxy can be used anywhere a Real Subject is expected.
  • Real Subject (Math)
     Defines the real object that the proxy represents.

Example Proxy Design Pattern:


using System; 
namespace Proxy.Structural
{
  /// <summary>
  /// MainApp startup class for Structural
  /// Proxy Design Pattern.
  /// </summary>
  class MainApp
  {
    /// <summary>
    /// Entry point into console application.
    /// </summary>
    static void Main()
    {
      // Create proxy and request a service
      Proxy proxy = new Proxy();
      proxy.Request(); 
      // Wait for user
      Console.ReadKey();
    }
  } 
  /// <summary>
  /// The 'Subject' abstract class
  /// </summary>
  abstract class Subject
  {
    public abstract void Request();
  } 
  /// <summary>
  /// The 'RealSubject' class
  /// </summary>
  class RealSubject : Subject
  {
    public override void Request()
    {
      Console.WriteLine("Called RealSubject.Request()");
    }
  } 
  /// <summary>
  /// The 'Proxy' class
  /// </summary>
  class Proxy : Subject
  {
    private RealSubject _realSubject; 
    public override void Request()
    {
      // Use 'lazy initialization'
      if (_realSubject == null)
      {
        _realSubject = new RealSubject();
      }

      _realSubject.Request();
    }
  }
}

Output
Called RealSubject.Request()


No comments:

Post a Comment