当前位置: 首页 > news >正文

C#观察者模式示例代码

using System;
using System.Collections.Generic;
using System.Threading;namespace RefactoringGuru.DesignPatterns.Observer.Conceptual
{// Observer观察者 也可以叫做订阅者 subscriberspublic interface IObserver{// Receive update from subject// 接收来自主题的更新void Update(ISubject subject);}// 拥有一些值得关注的状态的对象通常被称为目标, 由于它要将自身的状态改变通知给其他对象, 我们也将其称为发布者 (publisher)。public interface ISubject{// Attach an observer to the subject.// 加一个观察者。void Attach(IObserver observer);// Detach an observer from the subject.// 删一个观察者。void Detach(IObserver observer);// Notify all observers about an event.// 通知所有观察者 某一事件 void Notify();}// The Subject owns some important state and notifies observers when the// state changes.// 主题拥有一些重要的状态,并在状态发生变化时通知观察者。// 也可以叫发布者 Publisherpublic class Subject : ISubject{// For the sake of simplicity, the Subject's state, essential to all// subscribers, is stored in this variable.// 为了简便起见,主题的状态,对所有订阅者都至关重要的,存储在这个变量中。public int State { get; set; } = -0;// List of subscribers. In real life, the list of subscribers can be// stored more comprehensively (categorized by event type, etc.).// 订阅者列表。在现实生活中,订阅者列表可以更全面地存储(按事件类型等分类)。private List<IObserver> _observers = new List<IObserver>();// The subscription management methods.public void Attach(IObserver observer){Console.WriteLine("Subject: Attached an observer.");this._observers.Add(observer);}public void Detach(IObserver observer){this._observers.Remove(observer);Console.WriteLine("Subject: Detached an observer.");}// Trigger an update in each subscriber.// 在每个订阅者中触发更新public void Notify(){Console.WriteLine("Subject: Notifying observers...");foreach (var observer in _observers){observer.Update(this);}}// Usually, the subscription logic is only a fraction of what a Subject// can really do. Subjects commonly hold some important business logic,// that triggers a notification method whenever something important is// about to happen (or after it).// 通常,订阅逻辑只是主题真正能做的一小部分。主题通常包含一些重要的业务逻辑,每当重要的事情即将发生(或之后)时,就会触发通知方法。public void SomeBusinessLogic(){Console.WriteLine("\nSubject: I'm doing something important.");this.State = new Random().Next(0, 10);Thread.Sleep(15);Console.WriteLine("Subject: My state has just changed to: " + this.State);this.Notify();}}// Concrete Observers react to the updates issued by the Subject they had// been attached to.class ConcreteObserverA : IObserver{public void Update(ISubject subject){if ((subject as Subject).State < 3){Console.WriteLine("ConcreteObserverA: Reacted to the event.");}}}class ConcreteObserverB : IObserver{public void Update(ISubject subject){if ((subject as Subject).State == 0 || (subject as Subject).State >= 2){Console.WriteLine("ConcreteObserverB: Reacted to the event.");}}}class Program{static void Main(string[] args){// The client code.var subject = new Subject();var observerA = new ConcreteObserverA();subject.Attach(observerA);var observerB = new ConcreteObserverB();subject.Attach(observerB);subject.SomeBusinessLogic();subject.SomeBusinessLogic();subject.Detach(observerB);subject.SomeBusinessLogic();}}
}

输出:

Subject: Attached an observer.
Subject: Attached an observer.Subject: I'm doing something important.
Subject: My state has just changed to: 2
Subject: Notifying observers...
ConcreteObserverA: Reacted to the event.
ConcreteObserverB: Reacted to the event.Subject: I'm doing something important.
Subject: My state has just changed to: 1
Subject: Notifying observers...
ConcreteObserverA: Reacted to the event.
Subject: Detached an observer.Subject: I'm doing something important.
Subject: My state has just changed to: 5
Subject: Notifying observers...

 原文链接:

C# 观察者模式讲解和代码示例

仅供学习参考,如有侵权联系我删除

http://www.lryc.cn/news/599620.html

相关文章:

  • Idefics2:构建视觉-语言模型时,什么是重要的
  • ‌通向数字孪生的大门:掌握RVT到3DTiles的关键转换流程
  • 【NLP舆情分析】基于python微博舆情分析可视化系统(flask+pandas+echarts) 视频教程 - 主页-评论用户时间占比环形饼状图实现
  • 经验累积分布函数VS累积分布函数
  • Vue nextTick
  • 基于多模型AI训练与验证系统开发
  • 移动端设备能部署的llm
  • MC_GearInPos电子齿轮
  • Pytest tmp_path 实战指南:测试中的临时目录管理
  • 基于单片机的数字电压表设计
  • MyBatis-Plus 指南
  • 光耦合器:新能源世界的“绿色信使“
  • 全面解析MySQL(3)——CRUD进阶与数据库约束:构建健壮数据系统的基石
  • Krpano 工具如何调节全景图片切割之后的分辨率
  • 代码随想录算法训练营第三十一天
  • 卡尔曼滤波器噪声方差设置对性能影响的仿真研究
  • MATLAB 设置默认启动路径为上次关闭路径的方法
  • 【优选算法】链表
  • 从 SQL Server 到 KingbaseES V9R4C12,一次“无痛”迁移与深度兼容体验实录
  • UG创建的实体橘黄色实体怎么改颜色?
  • 每日算法-数组合并
  • [RPA] Excel中的字典处理
  • ubuntu22.04.4锁定内核应对海光服务器升级内核无法启动问题
  • CPU(中央处理器)和GPU(图形处理器)的区别
  • 在线事务型的业务、实时分析类业务、离线处理类型的业务
  • 如何提高微信小程序的应用速度
  • 代码随想录算法训练营第五十三天|图论part4
  • 基于spring boot的纺织品企业财务管理系统(源码+论文)
  • vue+iview+i18n国际化
  • Qt:qRegisterMetaType函数使用介绍