public class Program
{
static void Main(string[] args)
{
LoudSpeaker loudSpeaker = new LoudSpeaker();
Displayer displayer = new Displayer();
loudSpeaker.AddListen();
displayer.AddListen();
WaterHeater waterHeater = new WaterHeater();
waterHeater.BoilWater();
}
}
class WaterHeater//热水器/被观察者(主体)/被观察的数据载体
{
public delegate void Temperature(int temp);//委托监听水温
public static event Temperature temperature;
int _temperature = 0;
public void BoilWater()//烧水功能
{
do
{
_temperature++;
if (_temperature > 95)
{
temperature(_temperature);
}
}
while (_temperature < 100);
}
}
interface Observer//观察者监听接口
{
void AddListen();
void RemoveListen();
}
class LoudSpeaker : Observer//扬声器/观察者
{
public void AddListen()
{
WaterHeater.temperature += Speaker;
}
public void RemoveListen()
{
WaterHeater.temperature -= Speaker;
}
public void Speaker(int temp)//广播功能
{
Console.WriteLine("水快烧开了!");
}
}
class Displayer : Observer//显示器/观察者
{
public void AddListen()
{
WaterHeater.temperature += Show;
}
public void RemoveListen()
{
WaterHeater.temperature -= Show;
}
public void Show(int temp)//显示功能
{
Console.WriteLine("现在水温{0}度", temp);
}
}