C# 设计模式(20)观察者模式

观察者模式

代码实现:

事件类:

namespace ObserverPattern.Subject
{
    public class Cat
    {
        private readonly List<IObserver> _observerList = new List<IObserver>();

        public void AddObserver(IObserver observer)
        {
            _observerList.Add(observer);
        }

        public void RemoveObserver(IObserver observer)
        {
            _observerList.Remove(observer);
        }

        public void MeowObserver()
        {
            Console.WriteLine($"(Observer Mode) A cat Meow Suddenly!!");

            foreach (var observer in _observerList)
            {
                observer.DoAction();
            }
        }

        public event Action MeowEvent;

        public void OnMeowEvent()
        {
            Console.WriteLine($"(Event Mode) A cat Meow Suddenly!!");
            MeowEvent?.Invoke();
        }
    }
}

观察者类:

    public interface IObserver
    {
       public void DoAction();
    }
   public class Mouse:IObserver
    {
        public void DoAction()
        {
            Console.WriteLine($"{this.GetType().Name} Squeak and Run");
        }
    }
    public class Dog:IObserver
    {
        public void DoAction()
        {
            Console.WriteLine($"{this.GetType().Name} Woof Woof");
        }
    }

代码调用:

    class Program
    {
        static void Main(string[] args)
        {
            Cat cat = new Cat();
            IObserver mouse = new Mouse();
            IObserver dog = new Dog();

            //Observer
            Console.WriteLine("**********************************************");
            cat.AddObserver(mouse);
            cat.AddObserver(dog);
            cat.MeowObserver();
            Console.WriteLine("**********************************************");
            cat.RemoveObserver(dog);
            cat.MeowObserver();

            //Event
            Console.WriteLine("**********************************************");
            cat.MeowEvent += mouse.DoAction;
            cat.MeowEvent += dog.DoAction;
            cat.OnMeowEvent();
            Console.WriteLine("**********************************************");
            cat.MeowEvent -= dog.DoAction;
            cat.OnMeowEvent();
        }
    }

结果:

 

posted @ 2020-12-08 11:28  NiKaFace  阅读(216)  评论(0编辑  收藏  举报