编程语言
首页 > 编程语言> > C# 设计模式(20)观察者模式

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();
        }
    }

结果:

 

标签:Console,C#,void,cat,DoAction,WriteLine,20,设计模式,public
来源: https://www.cnblogs.com/YourDirection/p/14101695.html