四、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();
}
}