Programming - Proxy Structural Design Pattern


Provide a surrogate or placeholder for another object to control access to it.
The classes and/or objects participating in this example are:


  • Proxyand
    and
    • maintains a reference that lets the proxy access the real subject. Proxy may refer to a Subject if the RealSubject 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 responsibilites 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 ImageProxy from the Motivation caches the real images's extent.
      • protection proxies
        check that the caller has the access permissions required to perform a request.
  • Subjectand
    and
    • defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected.
  • RealSubjectand
    and and
    • defines the real object that the proxy represents.


// Proxy pattern -- Structural example

using
System;

namespace
DoFactory.GangOfFour.Proxy.Structural
{

// MainApp test application

class MainApp
{
static void Main()
{
// Create proxy and request a service
Proxy proxy = new Proxy();
proxy.Request();

// Wait for user
Console.Read();
}
}

// "Subject"

abstract class Subject
{
public abstract void Request();
}

// "RealSubject"

class RealSubject : Subject
{
public override void Request()
{
Console.WriteLine("Called RealSubject.Request()");
}
}

// "Proxy"

class Proxy : Subject
{
RealSubject realSubject;

public override void Request()
{
// Use 'lazy initialization'
if (realSubject == null)
{
realSubject = new RealSubject();
}

realSubject.Request();
}
}
}
Output expected:


Called RealSubject.Request()


Home | Privacy Policy | Site Map | Links | Company | Contact Us | Arena           

We provide cutting edge software development, consultancy and web design services            

There are currently 645 user(s) with 40588 hits.