C#观察者模式示例代码

cs 复制代码
using System;
using System.Collections.Generic;
using System.Threading;

namespace RefactoringGuru.DesignPatterns.Observer.Conceptual
{
    // Observer观察者 也可以叫做订阅者 subscribers
    public 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.
    // 主题拥有一些重要的状态,并在状态发生变化时通知观察者。
    // 也可以叫发布者 Publisher
    public 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();
        }
    }
}

输出:

XML 复制代码
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# 观察者模式讲解和代码示例

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

相关推荐
cimeo3 小时前
【C 学习】06-算法&程序设计举例
c#
百锦再4 小时前
.NET 的 WebApi 项目必要可配置项都有哪些?
java·开发语言·c#·.net·core·net
饕餮争锋12 小时前
设计模式笔记_行为型_观察者模式
笔记·观察者模式·设计模式
WYH28714 小时前
C#控制台输入(Read()、ReadKey()和ReadLine())
开发语言·c#
hqwest15 小时前
C#WPF实战出真汁06--【系统设置】--餐桌类型设置
c#·.net·wpf·布局·分页·命令·viewmodel
做一位快乐的码农18 小时前
基于.net、C#、asp.net、vs的保护大自然网站的设计与实现
c#·asp.net·.net
DavieLau19 小时前
C#项目WCF接口暴露调用及SOAP接口请求测试(Python版)
xml·服务器·开发语言·python·c#
张人玉19 小时前
C#Encoding
开发语言·c#
hqwest21 小时前
C#WPF实战出真汁05--左侧导航
开发语言·c#·wpf·主界面·窗体设计·视图viewmodel
melonbo21 小时前
中介者模式和观察者模式的区别是什么
观察者模式·中介者模式