close
1: // 訂閱者
2: public interface iObserver
3: {
4: void Update();
5: }
6: // 主題
7: public interface iSubject
8: {
9: void Add(iObserver observer); // 加入一個訂閱者
10: void Delete(iObserver observer); // 刪除一個訂閱者
11: void Notify(); // 通知訂閱者
12: }
主題
1: public class Subject : iSubject
2: {
3: private bool m_sent; // 判斷是否已經通知觀察者
4: public string infomation // 設定/取得 主題
5: {
6: get;
7: set;
8: }
9: // 紀錄觀察者
10: List<iObserver> m_observers = new List<iObserver>();
11: // 實作Add
12: public void Add(iObserver observer)
13: {
14: m_observers.Add(observer);
15: if (m_observers.Count >= 1)
16: {
17: m_sent = true;
18: }
19: else
20: {
21: m_sent = false;
22: }
23: }
24: // 實作Delete
25: public void Delete(iObserver observer)
26: {
27: m_observers.Remove(observer);
28: if( m_observers.Count >=1)
29: {
30: m_sent = true;
31: }
32: else
33: {
34: m_sent = false;
35: }
36: }
37: // 實作Notify
38: public void Notify()
39: {
40: if (m_sent)
41: {
42: foreach (iObserver o in m_observers)
43: {
44: o.Update();
45: }
46: m_sent = false;
47: }
48: }
49: }
訂閱者
1: // 訂閱者
2: public class Subsriber : iObserver
3: {
4: private string m_username; // 訂閱者名稱
5: private string m_infomation; // 訂閱者端接收主題
6: private Subject m_Subject; // 主題
7: // 建構子(傳入主題和訂閱者名稱)
8: public Subsriber(Subject subject, string username)
9: {
10: m_Subject = subject;
11: m_username = username;
12: }
13: // 訂閱某個主題
14: public Subject subscibe
15: {
16: get { return m_Subject; }
17: set { m_Subject = value; }
18: }
19: // 實作Update
20: public void Update()
21: {
22: m_infomation = m_Subject.infomation;
23: MessageBox.Show(string.Format("觀察者{0}, 收到資訊{1}", m_username, m_infomation));
24: }
25: }
-------------------------------------------------------------------------------------------------------------------------------------------------------
1: // 主題
2: Subject s = new Subject();
3: // 三個訂閱者
4: Subsriber user1, user2, user3;
5:
6: // (1)實體化三個訂閱者, 傳入主題和使用者名稱, 並訂閱主題
7: user1 = new Subsriber(s, "user #1");
8: s.Add(user1);
9:
10: user2 = new Subsriber(s, "user #2");
11: s.Add(user2);
12:
13: user3 = new Subsriber(s, "user #3");
14: s.Add(user3);
15:
16: // 設定主題名稱並通知訂閱者
17: s.infomation = "Hello World";
18: s.Notify();
1: // (2)主題刪除訂閱者2
2: s.Delete(user2);
3: s.infomation = "user #2 is deleted";
4: s.Notify();
下面這個使用狀況蠻有趣, 上一個例子則是主題主動刪除訂閱者
這次, 使用者透過內部成員函式Subject取得成員變數m_subject, 進而刪除自己達到取消訂閱的功能
1: // (3)訂閱者刪除訂閱主題
2: user3.subscibe.Delete(user3);
3: s.infomation = "Now notify user1 only";
4: s.Notify();
應用: 多個client(訂閱者)連線至server(主題), server決定哪些訂閱者有哪些功能(認證授權)及廣播功能
全站熱搜
留言列表