观察者模式

观察者模式概念:当一个事件触发的时候,同时另外几个事件也跟随触发。(狗叫了=》吓怕了小偷=》惊醒了主人)

实现方式有很多种,这里用c#的事件委托来实现。

第一种:原始的先建立委托,再创建事件

namespace 观察者模式
{
    public delegate void NotifyEventHandler(string sender);

    public class Cat
    {
        public event NotifyEventHandler CatEvent;


        public void Say()
        {
            Console.WriteLine("");
        }

        public void Cry(string info)
        {
            Console.WriteLine("猫叫了。。。");
            if (CatEvent!=null)
            {
                CatEvent(info);
            }
        }
             
    }

    public class Master
    {
        public void Wake(string name)
        {
            Console.WriteLine("惊醒了主人"+name);
        }
    }

    public class Mouse
    {
        public void Run(string name)
        {
            Console.WriteLine("吓跑了老鼠" + name);
        }
    }
}


namespace 观察者模式
{
    class Program
    {
        static void Main(string[] args)
        {
            Cat c = new Cat();
            Master m = new Master();
            Mouse mo = new Mouse();
            c.CatEvent += new NotifyEventHandler(m.Wake);
            c.CatEvent += mo.Run;
            c.Cry(":公众部分");

            Console.ReadKey();
        }
    }
}

 

第二种:直接用系统定义的委托Action来定义

namespace 观察者模式
{
    public class Observer
    {
        public event Action<string> action;

        public void Run(string notify)
        {
            Console.WriteLine("狗叫了" + notify);
            if (action!=null)
            {
                action(notify);
            }
        }
    }
}


namespace 观察者模式
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("=============");
            Observer os = new Observer();
            os.action += x => Console.WriteLine("惊醒了主人"+x);
            os.action += x => Console.WriteLine("吓跑了小偷"+x);
            os.Run("通知");

            Console.ReadKey();
        }
    }
}

 

posted @ 2018-08-06 15:17  zhuyapeng  阅读(194)  评论(0)    收藏  举报