C#设计模式:观察者模式(Observer Pattern)

一,什么是观察者模式(Observer Pattern)?

当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知它的依赖对象

二,代码如下:

在一开始我们先定义两个类,一个是Chinese类(被观察者) ,另一个是Jan类(观察者),观察者设计模式是当被观察者状态发生改变,从而触发观察者的事件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _16.观察者模式
{
    /// <summary>
    /// 当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知它的依赖对象
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Chinese ch = new Chinese("拿着棍子", "穿白色衣服的");
            Jan j1 = new Jan("灰衣服", ch);
            Jan j2 = new Jan("黑衣服", ch);
            ch.Coming();     //当中国人的状态发生改变,从而触发观察者绑定在中国人身上的事件(Coming)
            Console.ReadKey();
        }
    }
    public class Chinese
    {
        private string name;
        private string color;

        public Chinese(string name, string color)
        {
            this.name = name;
            this.color = color;
        }

        /// <summary>
        /// 中国人过来(中国人的状态发生改变)(被观察者的状态发生改变)
        /// </summary>
        public void Coming()
        {
            Console.WriteLine(color + "的中国人" + name + "过来了 ...");

            if (ActionCome != null)
                ActionCome();
        }

        public event Action ActionCome;  //声明一个事件 发布了一个消息
    }
    class Jan
    {
        private string color;

        public Jan(string color, Chinese cat)
        {
            this.color = color;
            cat.ActionCome += this.RunAway;//把自身的逃跑方法 注册进 中国人Coming事件里面  订阅消息
        }
        /// <summary>
        /// 逃跑功能
        /// </summary>
        public void RunAway()
        {
            Console.WriteLine(color + "的日本人说:赶紧跑");
        }
    }
}

 三,观察者模式的核心是使用Action将观察者事件绑定到被观察者中,这样我们就可以通过观察者时间异步通知被观察者

转载于:https://www.cnblogs.com/May-day/p/6367998.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值