zoukankan      html  css  js  c++  java
  • C#学习笔记-代理模式

    题目:A追B,但是羞于表示,所以A通过C给B一直送礼物以讨得欢心。

    分析:

    根据就分为三个类,SchoolGirl一个类,这个类只需要获得名字就好了;Pursuit一个类,这个类需要实现送礼物这个方法,需要设定他的追求对象是SchoolGirl;Proxy一个类,作为中间人,他并未准备礼物,所以他需要调用Pursuit的礼物类,同时他需要联系到SchoolGirl,已达到将礼物送至她手上的功能。

    接口:

     1      /**
     2      * 接口用于描述一组类的公共方法/公共属性. 
     3      * 它不实现任何的方法或属性,只是告诉继承它的类《至少》要实现哪些功能,
     4      * 继承它的类可以增加自己的方法. 
     5      */
     6     interface GiveGift
     7     {
     8         void GiveDolls();
     9         void GiveFlowers();
    10         void GiveChocolate();
    11     }
    View Code

    SchoolGirl类:

     1 class SchoolGirl
     2     {
     3         private string name;
     4 
     5         public string Name
     6         {
     7             get { return name; }
     8             set { name = value; }
     9         }
    10     }
    View Code

    Pursuit类:

     1 class Pursuit : GiveGift
     2     {
     3         SchoolGirl girl;
     4         public Pursuit(SchoolGirl mm)
     5         {
     6             this.girl = mm;
     7         }
     8 
     9         public void GiveDolls()
    10         {
    11             Console.WriteLine("give dolls for " + girl.Name);
    12         }
    13         public void GiveFlowers()
    14         {
    15             Console.WriteLine("give flowers for " + girl.Name);
    16         }
    17         public void GiveChocolate()
    18         {
    19             Console.WriteLine("give chocolate for " + girl.Name);
    20         }
    21     }
    View Code

    Proxy类:

     1  class Proxy : GiveGift
     2     {
     3         Pursuit boy;
     4         public Proxy(SchoolGirl mm)
     5         {
     6             boy = new Pursuit(mm);
     7         }
     8         public void GiveDolls()
     9         {
    10             boy.GiveDolls();
    11         }
    12         public void GiveFlowers()
    13         {
    14             boy.GiveFlowers();
    15         }
    16         public void GiveChocolate()
    17         {
    18             boy.GiveChocolate();
    19         }
    20     }
    View Code

     主函数:

     1 static void Main(string[] args)
     2         {
     3             SchoolGirl girl = new SchoolGirl();
     4             girl.Name = "Pretty";
     5 
     6             Proxy someone = new Proxy(girl);
     7 
     8             someone.GiveDolls();
     9             someone.GiveFlowers();
    10             someone.GiveChocolate();
    11 
    12             Console.Read();
    13         }
    View Code

    注:文中所有代码及知识点均来自于《大话设计模式》,本人属于边学边看边敲代码边总结的阶段。

  • 相关阅读:
    手机传感器大科普:手机中的陀螺仪、加速器和磁力计
    安卓新导入工程中gen目录下无R文件解决方法
    自写的 c# 锚点,前端显示 读书 记事本(一)
    update access 不能更新
    NHibenate初学资源推荐(切肤之痛)
    ASP.NET页面刷新和定时跳转
    c#(或vb.net)程序改进 (转载)
    感恩节的一天
    了解自己以及明白牛人会找什么样的人创业
    从别人如何读简历 看我们该如何成长
  • 原文地址:https://www.cnblogs.com/Aries-rong/p/7485224.html
Copyright © 2011-2022 走看看