观察者模式

来源:互联网 发布:h3c1024交换机端口镜像 编辑:程序博客网 时间:2024/06/07 01:15
 

 

本文章利用观察者模式模拟了赛场上跑步的情形。读者可以自己加一个类,啦啦队类,也作为一个观察者。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WindowsFormsApplication6
{

    //这里定义了一个委托类型,记住哦,他是个一个类型,和string是一样的。
    //他规定了一类函数,这类函数的参数都已经定义好了。
    //他其实定义了一个函数的指针。也就是函数的入口形式。
    public delegate void  actionHandler(object sender,EventArgs args);
    /// <summary>
    /// 发令员。其实他只知道发令,其实他啥也不知道,连哪些人
    /// 会接收他的消息都不知道。
    /// </summary>
   public class falingyuan
   {
       //public  actionHandler ActionHandler;如果只有一个接受者,也就只有一个处理函数。这个时候,
       //直接用委托就可以了。

       //如果接受者是多个对象,那么就会出现多个处理函数(委托所定义的函数类型),也就是函数列表,此时
       //可以用事件来表示,其实就是个函数列表。
      public event actionHandler ActionHandler;
      // public List<actionHandler> actions;

       public falingyuan()
       {
          //actions=new List<actionHandler>();
       }
       /// <summary>
       /// 我只会发令,不知道怎么办,如果你想听我的命令,那行
       /// 你得按照我的规格来办事,什么规格,就是委托定义的函数类型。
       /// </summary>
       public void faling()
       {
           //foreach (actionHandler ac in actions)
          // {
           actionHandler(this, null);
          // }
       }

        private string name;

       public string Name
       {
           get { return name; }
           set { name = value; }
       }
   }
}

//=====================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication6
{

    /// <summary>
    /// 运动员。
    /// </summary>
   public  class yundongyuan
    {
       public void Pao(object sender, EventArgs e)
       {
           MessageBox.Show("我听到了"+(sender as falingyuan).Name+"的枪响,我开始跑。");  
      
       }
    }
}

//==========================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication6
{
    /// <summary>
    /// 计时员
    /// </summary>
   public  class jishiyuan
    {
       public void jishi(object sender,EventArgs e)
       {
           MessageBox.Show("我看到了"+(sender as falingyuan).Name+"的枪发出的烟,我开始计时。");
       }

    }
}

//=========================================