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+" 洗澡中 ");
        }
    }

 附加图解 :

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

我加上 委托事件 再来搞搞

原文地址:https://www.cnblogs.com/atliwen/p/4844345.html