在C#中,實(shí)現(xiàn)實(shí)時(shí)通知的一種方法是使用觀察者模式(Observer Pattern)和事件(Events)。以下是一個(gè)簡單的示例,展示了如何創(chuàng)建一個(gè)觀察者、觸發(fā)器和一個(gè)訂閱者來實(shí)現(xiàn)實(shí)時(shí)通知。
public interface IObserver
{
void Update(string message);
}
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);
}
}
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)你的具體需求。