duminică, 22 noiembrie 2009

[DesignPatterns] Proxy Pattern

The Proxy pattern supports objects that control the creation of and access to other objects.
The proxy is often a small (public) object that stands in for a more complex (private) object that is activated once certain circumstances are clear.

Players:
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. Each Proxy object maintains a reference to a Subject
Request - An operation on the Subject that is routed via a proxy

Types of proxy:
Virtual proxies - Hands the creation of an object over to another object (useful if the creation process might be slow or might prove unnecessary)
Authentication proxies - Checks that the access permissions for a request are correct
Remote proxies - Encodes requests and send them across a network
Smart proxies - Adds to or change requests before sending them on

• Delaying the creation of a rich environment (virtual proxy)
• Logging in users (authentication proxy)
• Sending requests across the network (remote proxy)
• Performing actions on friends’ books (smart proxy)

Sample:

public interface IStat { string RequestValue(); }
public Stat : IStat {
public string Value { get; set; };
public string Name {get; set; };
public string RequestValue() { return this.Value} }

public class ProtectionProxy : IStat {
Stat m_stat;
string m_password = "1234";
public string Authenticate (string i_supplied)
{ if (i_supplied != m_password)
return "Protection Proxy: No access";
else
m_stat = new Subject( );
return "Protection Proxy: Authenticated";}

public string RequestValue( ) {
if (m_stat==null)
return "Protection Proxy: Authenticate first";
else return "Protection Proxy: Call to "+ m_stat.RequestValue( );}
}

Uses:
- to classes that have sensitive data or slow operations.
- in image-drawing systems
- any client/server system running on the .NET Framework

Niciun comentariu:

Trimiteți un comentariu