文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>C#观察者模式简例

C#观察者模式简例

时间:2011-05-13  来源:上校

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demo
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Cat cat = new Cat();
            Mouse mouse1 = new Mouse("小老鼠", cat);
            Mouse mouse2 = new Mouse("大老鼠", cat);
            Master master = new Master(cat);

            cat.Cry();
        }
    }

    public delegate void SubjectEventHandle();

    public abstract class Subject
    {
        public event SubjectEventHandle subEvent;

        protected void FireAway()
        {
            if (this.subEvent != null)
            {
                this.subEvent();
            }
        }
    }

    public class Cat : Subject
    {
        public void Cry()
        {
            HttpContext.Current.Response.Write("猫大叫一声。");
            this.FireAway();
        }

    }

    public abstract class Observer
    {
        public Observer(Subject sub)
        {
            sub.subEvent += new SubjectEventHandle(sub_subEvent);
        }

        public abstract void sub_subEvent();
    }

    public class Mouse : Observer
    {
        private string name;
        public Mouse(string name, Subject sub)
            : base(sub)
        {
            this.name = name;
        }

        public override void sub_subEvent()
        {
            HttpContext.Current.Response.Write(this.name + "赶紧跑了。");
        }
    }

    public class Master : Observer
    {
        public Master(Subject sub)
            : base(sub)
        {
       
        }

        public override void sub_subEvent()
        {
            HttpContext.Current.Response.Write("主人被吵醒了。");
        }
    }
}

相关阅读 更多 +
排行榜 更多 +
找茬脑洞的世界安卓版

找茬脑洞的世界安卓版

休闲益智 下载
滑板英雄跑酷2手游

滑板英雄跑酷2手游

休闲益智 下载
披萨对对看下载

披萨对对看下载

休闲益智 下载