zoukankan      html  css  js  c++  java
  • 10分钟让你完全理解观察者模式 版本二

    class Program
        {
            static void Main(string[] args)
            {
                // 事件源  
                Student student = new Student("美女"); 
                // 执行的事件
                student.Sleep();
                // 执行的时间
                student.Bathe();
                // 注册监听器
                student.SetStudentListener(new MyStudent()); 
    
            }
        }
    
        /// <summary>
        ///  事件源
        /// </summary>
        public class Student
        {
            public string Name { get; set; }
            // 事件接口 
            private IStudentListener _interface;
    
            public Student(string name)
            {
                this.Name = name;
            }
            public void Sleep()
            {
                Console.WriteLine(Name + " 睡觉了 ");
            } 
            public void Bathe()
            {
                if (_interface != null) 
                    _interface.Bathe(new EventObject(this)); 
                Console.WriteLine(Name + " 在洗澡 ");
            } 
            public void SetStudentListener(IStudentListener iListener)
            {
                this._interface = iListener;
            } 
        }
    
        /// <summary>
        /// 接口
        /// </summary>
        public interface IStudentListener
        {  // 监听的事件
            void Bathe(EventObject e);
        }
    
        /// <summary>
        ///  事件源   只是负责将处罚事件的对象经行传递过来
        /// </summary>
        public class EventObject
        { 
            private object _eOobj; 
    
            public EventObject(object o)
            {
                _eOobj = o;
            } 
            public object GetObject()
            {
                return _eOobj;
            } 
        }
    
        /// <summary>
        /// 监听者
        /// </summary>
        public class MyStudent : IStudentListener
        { 
            public void Bathe(EventObject e)
            {
                Student student = (Student)e.GetObject();
                Console.WriteLine(student.Name+" 洗澡中 ");
            }
        }

     附加图解 :

    自己胡乱花的  方便初学者 看而已    这种模式 一个事件 只能有一个监听者啊   一个动作 只能被一个人得知 。

    我加上 委托事件 再来搞搞

  • 相关阅读:
    我们工作为了什么
    为什么去国企(HP中华区总裁孙振耀退休感言)
    android中的所有activity间动画跳转
    [转]Eclipse进行可视化的GUI开发3大GUI插件
    用Monkey测试android程序
    大学之后拉开差距的原因
    dataset 和 datareader 区别
    曾经运行该线程的应用程序域已卸载。
    guid.tostring() 格式化指南
    vs 使用技巧
  • 原文地址:https://www.cnblogs.com/atliwen/p/4844345.html
Copyright © 2011-2022 走看看