用简单的例子,说明代理(Proxy)设计模式。
Insus.NET在家忙写程序没有时间,手机没钱了,叫儿子给一百元去超市(此超市有手机充值的服务)帮Insus.NET手机充值(话费)。
手机充值的事,Insus.NET会做,儿子也会做,但是Insus.NET因某些情况,不能亲自办,叫儿子去代理(Proxy)。定义一个抽象类[Work],让自己或是儿子类别都能实现的充值方法:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
using System;using System.Collections.Generic;using System.Linq;using System.Web;////// Summary description for Work/// namespace Insus.NET{ public abstract class Work { public abstract void Suppliement(); }}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
using System;using System.Collections.Generic;using System.Linq;using System.Web;////// Summary description for Self/// namespace Insus.NET{ public class Self : Work { public Self() { // // TODO: Add constructor logic here // } public override void Suppliement() { HttpContext.Current.Response.Write ("手机充值人民币100元"); } }}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
using System;using System.Collections.Generic;using System.Linq;using System.Web;////// Summary description for Son/// 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(); } }}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.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(); }}