用简单的例子,说明代理(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(); }}
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦