使用思路:
Client调用Request,非直接调用,而是在中间加入代理。例如:代理负责身份验证,如果验证失败,则返回错误。
这样处理有助于各类分工明确。不需要将验证等重复性的工作放入Client或Request内。
代理有好多种,最常用的包括:
虚拟代理 virtual proxies:负责实例化类,避免非必须的实例化。
认证代理 authentication proxies:检查一个请求是否拥有正确的访问许可。
远程代理 remote proxies:对请求进行编码并通过网络发送。
智能代理 smart proxies:在继续发送请求之前添加或更改请求。
例子
虚拟代理
public class Proxy : ISubject {
Subject subject;
public string Request() {
// 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();
}
}
在调用Request的时候,才实例化subject。