C#-观察者模式与事件

    class Cat
    {
        string name;
        string color;
        //public event delegate void catCome();自己声明的委托不能用于事件必须要Action,Func才可以
        public event Action catCome;
        public Cat(string name,string color)
        {
            this.name = name;
            this.color = color;
        }
        public void catComing()
        {
            
            Console.Write(name + "猫" + color + "来了");
            catCome();
        }
    }

    class Mouse
    {
        string name;
        string color;
        public Mouse(string name,string color,Cat c)
        {
            this.name = name;
            this.color = color;
            c.catCome+= RunAway;
        }
        public void RunAway()
        {
            Console.WriteLine("猫来了"+name+"要跑了");
        }
    }


namespace 事件与观察者模式
{
    /// <summary>
    /// 事件就是一种私有的委托实例,只能在内部触发,不能在外部触发,事件只能在外部被添加方法利用add,remove
    /// 观察者模式就是有一群观察者,和一个被观察者,被观察者里面定义一个事件,在内部合适的时机调用这个事件,这个事件是与观察者相关的
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Cat c = new Cat("加菲猫","黄色");
            Mouse mouse0 = new Mouse("老鼠1", "红色",c);
            Mouse mouse1 = new Mouse("老鼠2", "黑色",c);
            c.catComing();
            Console.ReadKey();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Icecoldless/article/details/82082742