程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#設計模式之Observer設計模式(觀察者設計模式)(3)

C#設計模式之Observer設計模式(觀察者設計模式)(3)

編輯:關於C語言

四、C#中的Delegate與Event

實際上在C#中實現Observer模式沒有這麼辛苦,.Net中提供了Delegate與Event機制,我們可以利用這種機制簡化Observer模式。關於Delegate與Event的使用方法請參考相關文檔。改進後的Observer模式實現如下:

// Observer pattern -- Structural example 
using System;
//Delegate
delegate void UpdateDelegate();
//Subject
class Subject
{
 public event UpdateDelegate UpdateHandler;
 // Methods
 public void Attach( UpdateDelegate ud )
 {
  UpdateHandler += ud;
 }
 public void Detach( UpdateDelegate ud )
 {
  UpdateHandler -= ud;
 }
 public void Notify()
 {
  if(UpdateHandler != null) UpdateHandler();
 }
}
//ConcreteSubject
class ConcreteSubject : Subject
{
 // FIElds
 private string subjectState;
 // PropertIEs
 public string SubjectState
 {
  get{ return subjectState; }
  set{ subjectState = value; }
 }
}
// "ConcreteObserver"
class ConcreteObserver
{
 // FIElds
 private string name;
 private string observerState;
 private ConcreteSubject subject;
 // Constructors
 public ConcreteObserver( ConcreteSubject subject, 
  string name )
 {
  this.subject = subject;
  this.name = name;
 }
 // Methods
 public void Update()
 {
  observerState = subject.SubjectState;
  Console.WriteLine( "Observer {0}'s new state is {1}",
   name, observerState );
 }
 // PropertIEs
 public ConcreteSubject Subject
 {
  get { return subject; }
  set { subject = value; }
 }
}
// "ConcreteObserver"
class AnotherObserver
{
 // Methods
 public void Show()
 {
  Console.WriteLine("AnotherObserver got an Notification!");
 }
}
public class ClIEnt
{
 public static void Main(string[] args)
 {
  ConcreteSubject s = new ConcreteSubject();
  ConcreteObserver o1 = new ConcreteObserver(s, "1");
  ConcreteObserver o2 = new ConcreteObserver(s, "2");
  AnotherObserver o3 = new AnotherObserver();
  s.Attach(new UpdateDelegate(o1.Update));
  s.Attach(new UpdateDelegate(o2.Update));
  s.Attach(new UpdateDelegate(o3.Show));
  s.SubjectState = "ABC";
  s.Notify();
  Console.WriteLine("--------------------------");
  s.Detach(new UpdateDelegate(o1.Update));
  s.SubjectState = "DEF";
  s.Notify();
 }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved