代理模式(Proxy):为其它对角提供一种代理以控制对这个对象的访问。
使用场合有以下几种:
第一:远程代理,也就是为一个对象在不同的地址空间提供局部代表。这样可以隐藏一个存在不同地址空间的事实。(WebService)
第二:虚拟代理,是根据需要创建开销很大的对象。通过它来存放实例化需要很长时间的对象。
第三:安全代理,用来控制真实对象的访问权限。
第四:智能指引,是指调用真实的对象时,代理处理另外一些事。
- using System;
- namespace StuDesignMode.Proxy
- {
- interface GiveGift
- {
- /// <summary>
- /// 送礼物
- /// </summary>
- void GiveDolls();
- /// <summary>
- /// 送鲜花
- /// </summary>
- void GiveFlowers();
- /// <summary>
- /// 送巧克力
- /// </summary>
- void GiveChocolate();
- }
- /// <summary>
- /// 被追求者,美女
- /// </summary>
- class Girl
- {
- public string Name { get; set; }
- public Girl(string name)
- {
- this.Name = name;
- }
- }
- /// <summary>
- /// 追求者
- /// </summary>
- class Pursuit : GiveGift
- {
- private Girl _mm;
- public Pursuit(Girl girl)
- {
- this._mm = girl;
- }
- public void GiveDolls()
- {
- Console.WriteLine("{0} 送你洋娃娃",this._mm.Name);
- }
- public void GiveFlowers()
- {
- Console.WriteLine("{0} 送你鲜花", this._mm.Name);
- }
- public void GiveChocolate()
- {
- Console.WriteLine("{0} 送你巧克力", this._mm.Name);
- }
- }
- /// <summary>
- /// 代理类,红娘
- /// </summary>
- class Proxyer : GiveGift
- {
- private Pursuit _gg;
- public Proxyer(Girl mm)
- {
- this._gg = new Pursuit(mm);
- }
- public void GiveDolls()
- {
- this._gg.GiveDolls();
- }
- public void GiveFlowers()
- {
- this._gg.GiveFlowers();
- }
- public void GiveChocolate()
- {
- this._gg.GiveChocolate();
- }
- }
- public class ClientTest
- {
- static void Main(string[] args)
- {
- Girl mm = new Girl("刘亦非");
- Proxyer huongniang = new Proxyer(mm);
- Console.WriteLine();
- huongniang.GiveDolls();
- huongniang.GiveFlowers();
- huongniang.GiveChocolate();
- Console.WriteLine();
- }
- }
- }