0
点赞
收藏
分享

微信扫一扫

高级FPGA开发之基础协议PCIe(二)

扬帆远航_df7c 02-12 07:30 阅读 5
c#

C#创建观察者设计模式,使用了事件。以下是如何在C#中使用事件实现观察者设计模式的示例:

using System;

// 发布者接口
public interface ISubject
{
    event EventHandler<string> Notify;
    void DoSomething();
}

// 具体发布者类
public class ConcreteSubject : ISubject
{
    public event EventHandler<string> Notify;

    public void DoSomething()
    {
        Console.WriteLine("主题正在做某事");
        Notify?.Invoke(this, "发生了某事");
    }
}

// 观察者接口
public interface IObserver
{
    void Update(object sender, string message);
}

// 具体观察者类
public class ConcreteObserver : IObserver
{
    public void Update(object sender, string message)
    {
        Console.WriteLine($"观察者收到消息: {message}");
    }
}

class Program
{
    static void Main()
    {
        // 创建发布者实例
        ISubject subject = new ConcreteSubject();

        // 创建观察者实例
        IObserver observer1 = new ConcreteObserver();
        IObserver observer2 = new ConcreteObserver();

        // 订阅事件
        subject.Notify += observer1.Update;
        subject.Notify += observer2.Update;

        // 发布者执行操作
        subject.DoSomething();

        Console.ReadLine();
    }
}

在这个示例中,ISubject接口定义了Notify事件和DoSomething方法。ConcreteSubject类实现了ISubject接口,并在调用DoSomething时触发Notify事件。

IObserver接口定义了Update方法,ConcreteObserver类实现了这个接口,用于处理事件通知。

Main方法中,创建了ConcreteSubject的实例,以及两个ConcreteObserver的实例,并订阅了主题的事件。当主题的DoSomething方法被调用时,它触发了事件并通知观察者。

当你运行这个示例时,你应该会看到如下输出:

主题正在做某事
观察者收到消息: 发生了某事
观察者收到消息: 发生了某事

这展示了在C#中使用事件实现的观察者设计模式。主题在事件发生时通知所有订阅的观察者。

举报

相关推荐

0 条评论