Proxy Pattern using C#
Proxy Pattern(代理模式)属于Structural Pattern(结构型模式),Proxy Pattern-为Client真正要调用的对象提供一个代理(Surrogate or placeholder),来控制Client对该对象的访问。
1. UML class diagram:
上图Proxy class就是一个代理类,负责转发来自Client的请求到真正的RealSubject对象。Proxy Class和RealSubject Class共同继承抽象类Subject。
2. Sample code
上述UML class diagram的实现代码(from reference 1):
// Proxy pattern –
Demo code
using
System;
//
抽象类
abstract
class Subject
{
abstract
public void Request();
}
//
实际要调用的类
class
RealSubject : Subject
{
override
public void Request()
{
Console.WriteLine("Called RealSubject.Request()");
}
}
//
代理类
class
Proxy : Subject
{
RealSubject realSubject;
// Methods
override
public void Request()
{
// Uses "lazy initialization"
if
( realSubject == null )
realSubject = new RealSubject();
realSubject.Request();
}
}
///
<summary>
///
Client test
///
</summary>
public
class Client
{
public
static void Main( string[] args )
{
// Create proxy and request a service
Proxy p = new Proxy();
p.Request();
}
}
3. Appendix about the article
温故而知新,运用于无形。
.Net Framework中大量使用到Proxy Design Pattern,如.Net Remoting中的SAO (Server Activated Object)或CAO (Client Activated Object),XML Web Services等,Client端都是通过本地Proxy class来转发对Remote Objects or Services的请求,和获取来自Remote的响应。
Reference:
1,Proxy Design Pattern, http://www.dofactory.com/patterns/PatternProxy.aspx