23种设计模式--观察者模式-Observer Pattern

一、观察者模式的介绍

     观察者模式从字面的意思上理解,肯定有两个对象一个是观察者,另外一个是被观察者,观察者模式就是当被观察者发生改变得时候发送通知给观察者,当然这个观察者可以是多个对象,在项目我们经常会用这些例子,这样避免了我们使用接口等那些依赖,比如电商项目中得降价通知,然后在来个生活中具体一点的比如公交车的例子,每一站都会对乘客进行提醒等等,我列举的这2个例子在我GITHUb上都有体现;下面用降价通知的Demo给大家具体来说一下,具体的代码还需要大家去下载观看;

二、观察者模式Demo

/// <summary>
    /// 商品类
    /// 11-14 wtz编写
    /// </summary>
    public class Commodity
    {
        /// <summary>
        /// 与Person类解藕,不需要再借助接口的形式进行业务之间的解耦
        /// </summary>
        /// <param name="sender"></param>
        public delegate void NotifyEventHandler(object sender);

        public NotifyEventHandler NotifyEvent;

        private string _name;

        private double _price;

        public Commodity(string name,double price)
        {
            this._name = name;
            this._price = price;
        }

        public string name
        {
            get { return _name; }
            set { _name = value; }
        }

        public double price
        {
            get { return _price; }
            set { _price = value; }
        }

        public void Send()
        {
            if (NotifyEvent != null)
            {
                NotifyEvent(this);
            }

        }
    }

/// <summary>
    /// 通知的人的类
    /// 11-14 wtz
    /// </summary>
    public class Person
    {

        private string _name;
        public Person(string name)
        {
            this._name = name;
        }

        public void Receive(object obj)
        {
            if (obj is Commodity)
            {
                Commodity commodity = (Commodity)obj;
                Console.WriteLine(this._name + "收到了" + commodity.name + "的降价通知邮件现在价格为" + commodity.price);
            }
        }
    }

/// <summary>
    /// 控制台执行的代码
    /// 11-14 wtz
    /// </summary>

Person person = new Person("小王");
            Commodity commodity = new Commodity("手机", 100.8);
            commodity.NotifyEvent +=new Commodity.NotifyEventHandler(person.Receive);
            commodity.Send();
            Console.ReadKey();

三、GitHub

       https://github.com/wangtongzhou520/Designpattern

上一篇:Visual Studio Code 1.27 发布,新特性来袭


下一篇:常用的SpringBoot时间格式化