设计模式笔记(五) —— 代理模式

来源:互联网 发布:可牛闪图软件下载 编辑:程序博客网 时间:2024/06/08 08:33

 代理模式(Proxy):为其它对角提供一种代理以控制对这个对象的访问。
   使用场合有以下几种:
   第一:远程代理,也就是为一个对象在不同的地址空间提供局部代表。这样可以隐藏一个存在不同地址空间的事实。(WebService)
   第二:虚拟代理,是根据需要创建开销很大的对象。通过它来存放实例化需要很长时间的对象。
   第三:安全代理,用来控制真实对象的访问权限。
   第四:智能指引,是指调用真实的对象时,代理处理另外一些事。

  1. using System;
  2. namespace StuDesignMode.Proxy
  3. {
  4.     interface GiveGift
  5.     {
  6.         /// <summary>
  7.         /// 送礼物
  8.         /// </summary>
  9.         void GiveDolls();
  10.         /// <summary>
  11.         /// 送鲜花
  12.         /// </summary>
  13.         void GiveFlowers();
  14.         /// <summary>
  15.         /// 送巧克力
  16.         /// </summary>
  17.         void GiveChocolate();
  18.     }
  19.     /// <summary>
  20.     /// 被追求者,美女
  21.     /// </summary>
  22.     class Girl
  23.     {
  24.         public string Name { getset; }
  25.         public Girl(string name)
  26.         {
  27.             this.Name = name;
  28.         }
  29.     }
  30.     /// <summary>
  31.     /// 追求者
  32.     /// </summary>
  33.     class Pursuit : GiveGift
  34.     {
  35.         private Girl _mm;
  36.         public Pursuit(Girl girl)
  37.         {
  38.             this._mm = girl;   
  39.         }
  40.         public void GiveDolls()
  41.         {
  42.             Console.WriteLine("{0} 送你洋娃娃",this._mm.Name);
  43.         }
  44.         public void GiveFlowers()
  45.         {
  46.             Console.WriteLine("{0} 送你鲜花"this._mm.Name);
  47.         }
  48.         public void GiveChocolate()
  49.         {
  50.             Console.WriteLine("{0} 送你巧克力"this._mm.Name);
  51.         }
  52.     }
  53.     /// <summary>
  54.     /// 代理类,红娘
  55.     /// </summary>
  56.     class Proxyer : GiveGift
  57.     {
  58.         private Pursuit _gg;
  59.         public Proxyer(Girl mm)
  60.         {
  61.             this._gg = new Pursuit(mm);
  62.         }
  63.         public void GiveDolls()
  64.         {
  65.             this._gg.GiveDolls();
  66.         }
  67.         public void GiveFlowers()
  68.         {
  69.             this._gg.GiveFlowers();
  70.         }
  71.         public void GiveChocolate()
  72.         {
  73.             this._gg.GiveChocolate();
  74.         }
  75.     }
  76.     public class ClientTest
  77.     {
  78.         static void Main(string[] args)
  79.         {
  80.             Girl mm = new Girl("刘亦非");
  81.             Proxyer huongniang = new Proxyer(mm);
  82.             Console.WriteLine();
  83.             huongniang.GiveDolls();
  84.             huongniang.GiveFlowers();
  85.             huongniang.GiveChocolate();
  86.             Console.WriteLine();
  87.         }
  88.     }
  89. }
原创粉丝点击