Welcome

首页 / 软件开发 / C# / 无废话C#设计模式之九:Proxy

无废话C#设计模式之九:Proxy2010-01-13 博客园 lovecherry意图

为其他对象提供一种代理以控制对这个对象的访问。

场景

代理模式非常常用,大致的思想就是通过为对象加一个代理来降低对象的使用复杂度、或是提升对象使用的友好度、或是提高对象使用的效率。在现实生活中也有很多代理的角色,比如明星的经纪人,他就是一种代理,经纪人为明星处理很多对外的事情,目的是为了节省被代理对象也就是明星的时间。保险代理人帮助投保人办理保险,目的降低投保的复杂度。

在开发中代理模式也因为目的不同效果各不相同。比如,如果我们的网站程序是通过.NET Remoting来访问帐号服务的。在编写代码的时候可能希望直接引用帐号服务的DLl ,直接实例化帐号服务的类型以方便调试。那么,我们可以引入Proxy模式,做一个帐号服务的代理,网站只需要直接调用代理即可。在代理内部实现正式和测试环境的切换,以及封装调用.NET Remoting的工作。

示例代码

using System;

using System.Collections.Generic;

using System.Text;

namespace ProxyExample

{

class Program

{

static void Main(string[] args)

{

AccountProxy ap = new AccountProxy();

ap.Register();

}

}

interface IAccount

{

void Register();

}

class Account : IAccount

{

public void Register()

{

System.Threading.Thread.Sleep(1000);

Console.WriteLine("Done");

}

}

class AccountProxy : IAccount

{

readonly bool isDebug = true;

IAccount account;

public AccountProxy()

{

if (isDebug)

account = new Account();

else

account = (IAccount)Activator.GetObject(typeof(IAccount), "uri");

}

public void Register()

{

Console.WriteLine("Please wait...");

account.Register();

}

}

}