用简单的例子,说明代理(Proxy)设计模式。
Insus.NET在家忙写程序没有时间,手机没钱了,叫儿子给一百元去超市(此超市有手机充值的服务)帮Insus.NET手机充值(话费)。
手机充值的事,Insus.NET会做,儿子也会做,但是Insus.NET因某些情况,不能亲自办,叫儿子去代理(Proxy)。
定义一个抽象类[Work],让自己或是儿子类别都能实现的充值方法:
Work
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(); }}
当自己没有特殊情况,或是有时间的情况之,自己去超市对手机充值:
Self
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的手机充值:
Son
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网页:
ProxyDemo.aspx.cs
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(); }}
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦