溫馨提示×

c# watcher如何實(shí)現(xiàn)實(shí)時(shí)通知

c#
小樊
81
2024-09-24 17:26:04
欄目: 編程語言

在C#中,實(shí)現(xiàn)實(shí)時(shí)通知的一種方法是使用觀察者模式(Observer Pattern)和事件(Events)。以下是一個(gè)簡單的示例,展示了如何創(chuàng)建一個(gè)觀察者、觸發(fā)器和一個(gè)訂閱者來實(shí)現(xiàn)實(shí)時(shí)通知。

  1. 首先,創(chuàng)建一個(gè)表示觀察者的接口:
public interface IObserver
{
    void Update(string message);
}
  1. 接下來,創(chuàng)建一個(gè)表示觸發(fā)器的類,該類包含事件和添加/刪除觀察者的方法:
public class Notifier
{
    // 事件
    public event Action<string> OnNotification;

    // 添加觀察者
    public void AddObserver(IObserver observer)
    {
        OnNotification += observer.Update;
    }

    // 刪除觀察者
    public void RemoveObserver(IObserver observer)
    {
        OnNotification -= observer.Update;
    }

    // 觸發(fā)通知
    public void Notify(string message)
    {
        OnNotification?.Invoke(message);
    }
}
  1. 最后,創(chuàng)建一個(gè)表示訂閱者的類,該類實(shí)現(xiàn)觀察者接口:
public class Watcher : IObserver
{
    private string _name;

    public Watcher(string name)
    {
        _name = name;
    }

    public void Update(string message)
    {
        Console.WriteLine($"{_name} received notification: {message}");
    }
}

現(xiàn)在,你可以創(chuàng)建一個(gè)Notifier實(shí)例和一個(gè)Watcher實(shí)例,并將觀察者添加到觸發(fā)器中:

public static void Main(string[] args)
{
    Notifier notifier = new Notifier();
    Watcher watcher = new Watcher("Watcher1");

    notifier.AddObserver(watcher);

    // 模擬實(shí)時(shí)通知
    notifier.Notify("Hello, Observer!");

    // 移除觀察者
    notifier.RemoveObserver(watcher);
}

運(yùn)行此代碼,你將看到Watcher1在接收到通知時(shí)輸出一條消息。你可以根據(jù)需要修改這個(gè)示例,以適應(yīng)你的具體需求。

0