找人办事,代理设计模式(Proxy)
用简单的例子,说明代理(Proxy)设计模式。
Insus.NET在家忙写程序没有时间,手机没钱了,叫儿子给一百元去超市(此超市有手机充值的服务)帮Insus.NET手机充值(话费)。
手机充值的事,Insus.NET会做,儿子也会做,但是Insus.NET因某些情况,不能亲自办,叫儿子去代理(Proxy)。
定义一个抽象类[Work],让自己或是儿子类别都能实现的充值方法:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for Work /// </summary> namespace Insus.NET { public abstract class Work { public abstract void Suppliement(); } }
当自己没有特殊情况,或是有时间的情况之,自己去超市对手机充值:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for Self /// </summary> namespace Insus.NET { public class Self : Work { public Self() { // // TODO: Add constructor logic here // } public override void Suppliement() { HttpContext.Current.Response.Write ("手机充值人民币100元"); } } }
事情代办,叫儿子去帮Insus.NET的手机充值:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for Son /// </summary> namespace Insus.NET { public class Son: Work { Self objSelf; public Son() { // // TODO: Add constructor logic here // } public override void Suppliement() { if (objSelf == null) { objSelf = new Self(); } objSelf.Suppliement(); } } }
asp.net运行程序,在站点建立一个aspx网页:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Insus.NET; public partial class ProxyDemo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //自己为Insus.NET手机充值 Self objSelf = new Self(); objSelf.Suppliement(); //儿子(代理)为Insus.NET手机充值。 Son objSon = new Son(); objSon.Suppliement(); } }