Tuesday, June 24, 2008

Proxy Design Pattern

The Proxy pattern controlling the creation and access to other objects.


Use the Proxy pattern when You have objects that:


• Are expensive to create.


• Need access control.


• Access remote sites.


• Need to perform some action whenever they are accessed.


The design of a proxy and its players is shown in the UML diagram




The players in the pattern are:
ISubject : A common interface for subjects and proxies that enables them to be used Interchangeably.
Subject :The class that a proxy represents.
Proxy : A class that creates, controls, enhances, and authenticates access to a Subject
Request : An operation on the Subject that is routed via a proxy
And this the implementation :
using System;
// Proxy Pattern Judith Bishop Dec 2006
// Shows virtual and protection proxies
class SubjectAccessor {

public interface ISubject

{
string Request ( );
}
private class Subject

{
public string Reques( ) {
return "Subject Request " + "Choose left door\n";
}
}
public class Proxy : ISubject

{
Subject subject;
public string Reques( ) {
// A virtual proxy creates the object only on its first method call
if (subject == null) {
Console.WriteLine("Subject inactive");
subject = new Subject( );
}
Console.WriteLine("Subject active");
return "Proxy: Call to" + subject.Request( );

}
}
public class ProtectionProxy :ISubject {
// An authentication proxy first asks for a password
Subject subject;
string password = "Abracadabra";
public string Authenticate(string supplied)

{
if (supplied!=password) return "Protection Proxy: No access";
else
subject = new Subject( );
return
"Protection Proxy: Authenticated";
}
public string Request( )

{
if (subject==null)
return "Protection Proxy: Authenticate first";
else
return "Protection Proxy: Call to "+
subject.Request( );
}
}
}
class Client : SubjectAccessor

{

static void Main( ) {
Console.WriteLin("Proxy Pattern\n");
ISubject subject = new Proxy( );
Console.WriteLine(subject.Request( ));
Console.WriteLine(subject.Request( ));
subject = new ProtectionProxy( );
Console.WriteLine(subject.Request( ));
Console.WriteLine((subject as ProtectionProxy).Authenticate("Secret"));
Console.WriteLine((subject as ProtectionProxy).Authenticate("Abracadabra"));
Console.WriteLine(subject.Request( ));
Console.ReadLine();
}
}


/* Output
Proxy Pattern
Subject inactive
Subject active

Proxy: Call to Subject Request Choose left door

Subject active
Proxy: Call to Subject Request Choose left door
Protection Proxy: Authenticate first
Protection Proxy: No access
Protection Proxy: Authenticated
Protection Proxy: Call to Subject Request Choose left door


*/




The central class, Proxy, implements the ISubject interface. The Client can use


ISubject to abstract away from proxies. Each Proxy object maintains a reference to a Subject, which is where the action really takes place.

No comments: