2009年11月2日星期一

Observer观察者设计模式

Observer观察者设计模式,和计算机系统的中断的概念非常类似。CPU(作为观察者)对外部设备的变化,比如键盘的输入,鼠标的点击等,不是去不断的循环检测,而是当外部设备有变化时,主动产生一个中断,告诉CPU,这样就可以让CPU有更多的精力处理其他业务。
现实生活中,比如投资股票的投资者,一种方式是1整天的开盘时间都盯着股票的价格牌,另一种方式是通过一个观察者(比如手机短信),只有当价格变化的时候通知投资者,这样投资者就可以在股票没有变化的时候做其他事情。这就是Observer设计模式的概念。这个例子用程序实现如下:

/// Observer Design Pattern
class MainApp
{
static void Main()
{
//创建Google的股票,设定初始价格120.00
Google google = new Google("Google", 120);
//创建2位投资者,并且设定投资Google的股票。
google .Attach(new Investor("Tom"));
google .Attach(new Investor("Kate"));

//Google价格变动,主动通知投资者Tom和Kate
google .Price = 121;
google .Price = 122;
google .Price = 123;
google .Price = 124;
// Wait for user
Console.ReadKey();
}
}
//股票的抽象类
abstract class Stock
{
private string _symbol;//股票名称
private double _price;//股票价格
//投资者列
private List _investors = new List();

// Constructor
public Stock(string symbol, double price)
{
this._symbol = symbol;
this._price = price;
}
//投资该股票的投资者
public void Attach(IInvestor investor)
{
_investors.Add(investor);
}
//投资者退出投资该股票
public void Detach(IInvestor investor)
{
_investors.Remove(investor);
}
//股票价格变动的时候,通知所有投资该股票投资者
public void Notify()
{
foreach (IInvestor investor in _investors)
{
investor.Update(this);
}
Console.WriteLine("");
}

// 设置该股票的价格
public double Price
{
get { return _price; }
set
{
//触发价格更新事件
if (_price != value)
{
_price = value;
Notify();
}
}
}
// 取得股票名称
public string Symbol
{
get { return _symbol; }
}
}

//Google的股票类
class Google : Stock
{
// Constructor
public Google(string symbol, double price)
: base(symbol, price)
{
}
}
//投资者的接口
interface IInvestor
{
void Update(Stock stock);
}
//投资者类
class Investor : IInvestor
{
private string _name;
private Stock _stock;
// Constructor
public Investor(string name)
{
this._name = name;
}
//股票价格变动时,通知投资者更新股票价格
public void Update(Stock stock)
{
Console.WriteLine("Notified {0} of {1}'s " +
"change to {2:C}", _name, stock.Symbol, stock.Price);
}

// 投资者投资的股票。
public Stock Stock
{
get { return _stock; }
set { _stock = value; }
}
}

执行结果:
Notified Tom of Google's change to \121
Notified Kate of Google's change to \121

Notified Tom of Google's change to \122
Notified Kate of Google's change to \122

Notified Tom of Google's change to \123
Notified Kate of Google's change to \123

Notified Tom of Google's change to \124
Notified Kate of Google's change to \124

没有评论:

发表评论