2007 |
Section 7, Chapter 4 |
Proxy Pattern
Concept
Proxies generally provide a stub or placeholder for an actual implementation object. It allows the creation, security, or accessibility to be handled outside the current code domain, or latently handled on another address space.
Use
We wish to hide and encapsulate the security protocols, initialization, and instance creation of the Subject object. In addition, we need a way to share desired functionality either remotely or between otherwise incompatible domains.
Design
Four different types:
- Remote Proxy
- Virtual Proxy
- Protection Proxy
- Smart Reference/Smart Pointer
Illustration
The proxy object will handle how and when we create our Subject object implementation. It will also mask any initialization and the pointer into the domain where the Subject object exists.
// Subject
public interface ISubject
{
string GetRequest();
}
// RealSubject
class Subject : MarshalByRefObject, ISubject
{
public string GetRequest(){ return "Request Found"; }
}
// Remote Proxy Object
class SubjectProxy : ISubject
{
private ISubject _subject;
public SubjectProxy(
string domainName,
System.Security.Policy.Evidence evidence,
System.AppDomainSetup appSetup)
{
AppDomain domain = System.AppDomain.CreateDomain(domainName, evidence, appSetup);
//creates a {System.Runtime.Remoting.Proxies.__TransparentProxy}
//proxy stub to Examples.Proxy.Subject
_subject = (ISubject)domain.CreateInstanceAndUnwrap("Examples", "Examples.Proxy.Subject");
}
public string GetRequest()
{
return _subject.GetRequest();
}
}
// Specify the domain details
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = path;
setup.ConfigurationFile = "(some file)";
// Set up the Evidence
Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
Evidence evidence = new Evidence(baseEvidence);
evidence.AddAssembly("(some assembly)");
evidence.AddHost("(some host)");
SubjectProxy proxy = new SubjectProxy("SubjectDomain", evidence, setup);
return proxy.GetRequest();