Welcome

首页 / 软件开发 / 数据结构与算法 / 从一个小实例开始 - Boo开篇

从一个小实例开始 - Boo开篇2011-10-01前一阵小组内部培训时,提到下面这个例子:

“假设我们有个高档的热水器,我们给它通上电,当水温超过95度的时候:

1、警报器会开始发出语音,告诉你水的温度;

2、显示器也会改变水温的显示,提示水已经快烧开了。 ”

相信大家能很快明白这是GoF设计模式中典型的Observer模式,下面我想通过这个例子用Boo实现来作为Boo系列的开篇。

在继续之前,为了方便大家看到C#与Boo两者在语法上的不同,我先写出C#下Observer模式的实现(采用事件机制):

#region C# Observer Pattern
public delegate void NotifyEventHandler(Heater heater);
public class Heater
{
public event NotifyEventHandler Notify = delegate { };
public int Temperature {
get;
set;
}
public void Boil() {
if (Temperature > 95)
Notify(this);
}
}
public abstract class Device
{
public virtual void Update(Heater heater) {
Do();
Console.WriteLine("The water is boiling! Water temperature is {0}", heater.Temperature);
}
protected abstract void Do();
}
public class Alarm : Device
{
protected override void Do() {
Console.WriteLine("Alarm!");
}
}
public class Monitor : Device
{
protected override void Do() {
Console.WriteLine("Monitor!");
}
}
#endregion