委托 事件 实现观察者模式

通过委托事件 实现观察者模式



通过委托事件 实现观察者模式

一些简单的类

public class Student
    {
        public delegate void StudentDelegate();
        public event StudentDelegate StudentPlayPhone;
        public void PlayPhone()
        {
            Console.WriteLine("学生拿出了手机");
            if (StudentPlayPhone != null)
            {
                StudentPlayPhone.Invoke();
            }
        }
    }
public class Teacher
    {
        public static void CatchHim()
        {
            Console.WriteLine("老师抓到他,找家长");
        }
    }


public class Mom
    {
        public static void Criticism()
        {
            Console.WriteLine("妈妈批评");
        }
    }


 public class Dad
    {
        public static void Struck()
        {
            Console.WriteLine("爸爸揍");        
        }
    }


调用


 class Program
    {
        static void Main(string[] args)
        {
            //观察者模式
            Student s = new Student();
            s.StudentPlayPhone += Teacher.CatchHim;
            s.StudentPlayPhone += Mom.Criticism;
            s.StudentPlayPhone += Dad.Struck;
            s.PlayPhone();
 
            Console.Read();
        }
    }

结果

http://owfile.aiyouhe.com/Upload/Img/c21ac2b2-dbd9-4306-bd15-db05229b93e5.png


>