/// <summary>
/// 抽象观察者接口
/// </summary>
interface Observer
{
void Update();
}
/// <summary>
/// 具体观察者
/// </summary>
class ConcreteObserver : Observer
{
string _name;
string _observerState;
ConcreteSubject _subject;
public ConcreteSubject Subject
{
get { return _subject; }
set { _subject = value; }
}
public ConcreteObserver(ConcreteSubject sub, string name)
{
this._subject = sub;
this._name = name;
}
public void Update()
{
_observerState = Subject.SubjectState;
Console.WriteLine(string.Format("通知{0}:{1}, no stock", _name, _observerState));
}
}
/// <summary>
/// 抽象发布类
/// </summary>
abstract class Subject
{
private IList<Observer> observers = new List<Observer>();
public void Attach(Observer ob)
{
observers.Add(ob);
}
public void Detach(Observer ob)
{
observers.Remove(ob);
}
public void Notify()
{
foreach (Observer ob in observers)
{
ob.Update();
}
}
}
/// <summary>
/// 具体发布类
/// </summary>
class ConcreteSubject : Subject
{
string subjectState;
public string SubjectState
{
get { return subjectState; }
set { subjectState = value; }
}
}
// 业务代码
ConcreteSubject sub = new ConcreteSubject();
sub.Attach(new ConcreteObserver(sub, "x"));
sub.Attach(new ConcreteObserver(sub, "y"));
sub.SubjectState = "ABC";
sub.Notify();
但是并不是每个观察者都会有 Update 这个方法,因此:
/// <summary>
/// 具体观察者
/// </summary>
class ConcreteObserver
{
string _name;
Subject _sub;
public ConcreteObserver(string name, Subject sub)
{
this._name = name;
this._sub = sub;
}
public void Closing()
{
Console.WriteLine(string.Format("通知{0}:{1} : Close, no stock", _name, _sub.SubjectState));
}
public void Open()
{
Console.WriteLine(string.Format("通知{0}:{1} : Open, no stock", _name, _sub.SubjectState));
}
}
/// <summary>
/// 抽象发布类
/// </summary>
interface Subject
{
void Notify();
string SubjectState
{
get;
set;
}
}
delegate void EventHandler();
class Boss : Subject
{
string action;
public string SubjectState
{
get { return action; }
set { action = value; }
}
public event EventHandler Update;
public void Notify()
{
Update();
}
}
// 业务代码
Boss hu = new Boss();
ConcreteObserver ob1 = new ConcreteObserver("boyA", hu);
ConcreteObserver ob2 = new ConcreteObserver("boyB", hu);
hu.Update += new EventHandler(ob1.Closing);
hu.Update += new EventHandler(ob2.Open);
hu.SubjectState = "I am Coming";
hu.Notify();