首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

觀察者模式 C# 範例:主題與觀察者介面實作

     編輯:關於C語言

介面定義

public interface ISubject { void Attach(IObserver obs); }
public interface IObserver { void Update(); }

具體主題


public class Subject : ISubject
{
    ArrayList observers = new ArrayList();
    public void Attach(IObserver obs) => observers.Add(obs);
    public void Notify()
    {
        Console.WriteLine("Subject notifying...");
        foreach (IObserver o in observers) o.Update();
    }
}

具體觀察者


public class ObserverA : IObserver
{
    string name; ISubject subject;
    public ObserverA(string name, ISubject sub) { this.name = name; subject.Attach(this); }
    public void Update() => Console.WriteLine($"{name} received notification.");
}

public class ObserverB : IObserver
{
    string name; ISubject subject;
    public ObserverB(string name, ISubject sub) { this.name = name; subject.Attach(this); }
    public void Update() => Console.WriteLine($"{name} got the news!");
}

用戶端測試


class Program
{
    static void Main()
    {
        ISubject sub = new Subject();
        new ObserverA("ObserverA", sub);
        new ObserverB("ObserverB", sub);
        sub.Notify();
    }
}

輸出

Subject notifying...
ObserverA received notification.
ObserverB got the news!

模式優點

  • 主題與觀察者解耦,符合依賴倒置原則。
  • 支援動態增減觀察者。
  • 廣播機制簡單高效。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved