A Sort Of A Blog
旧游无处不堪寻,无寻处,惟有少年心
设计模式-代理

代理模式(Proxy Pattern)是一种结构型设计模式,让你能够提供对象的替代品或其占位符。代理控制着对于原对象的访问,并允许在将请求提交给对象前后进行一些处理。

代理模式 UML


适用场景


  1. 延迟初始化。如果你有一个偶尔使用的重量级服务对象,一直保持该对象运行会消耗系统资源时,可使用代理模式
  2. 访问控制。如果你只希望特定客户端使用服务对象,这里的对象可以是操作系统中非常重要的部分,而客户端则是各种已启动的程序(包括恶意程序),此时可使用代理模式

代码示例


using System;
namespace ProxyPatternDemo
{
public interface ISubject
{
void Request();
}

class RealSubject : ISubject
{
public void Request()
{
Console.WriteLine("RealSubject: Handling Request.");
}
}

class Proxy : ISubject
{
private RealSubject _realSubject;

public Proxy(RealSubject realSubject)
{
this._realSubject = realSubject;
}

public void Request()
{
if (this.CheckAccess())
{
this._realSubject.Request();

this.LogAccess();
}
}

public bool CheckAccess()
{
Console.WriteLine("Proxy: Checking access prior to firing a real request.");

return true;
}

public void LogAccess()
{
Console.WriteLine("Proxy: Logging the time of request.");
}
}

public class Client
{
public void ClientCode(ISubject subject)
{
// ...

subject.Request();

// ...
}
}

class Program
{
static void Main(string[] args)
{
Client client = new Client();

Console.WriteLine("Client: Executing the client code with a real subject:");
RealSubject realSubject = new RealSubject();
client.ClientCode(realSubject);

Console.WriteLine();

Console.WriteLine("Client: Executing the same client code with a proxy:");
Proxy proxy = new Proxy(realSubject);
client.ClientCode(proxy);
// output

// Client: Executing the client code with a real subject:
// RealSubject: Handling Request.

// Client: Executing the same client code with a proxy:
// Proxy: Checking access prior to firing a real request.
// RealSubject: Handling Request.
// Proxy: Logging the time of request.
}
}
}