• C#观察者模式简例


    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("主人被吵醒了。");
            }
        }
    }

  • 相关阅读:
    CentOS7下部署Django
    ORM动态创建表
    JQuery制作加载进度条
    文件上传、下载
    Django执行事务操作
    python常用代码
    深入理解Java虚拟机-垃圾收集器
    ILRuntime作者林若峰分享:次世代手游渲染怎么做
    Android:手把手教你构建 全面的WebView 缓存机制 & 资源加载方案
    unity3d 热更篇--ILRuntime原理
  • 原文地址:https://www.cnblogs.com/zhuawang/p/2044996.html
Copyright © 2020-2023  润新知