假设我们有个高档的热水器,我们给它通上电,当水温超过95度的时候:
1、扬声器会开始发出语音,告诉你水的温度
2、液晶屏也会改变水温的显示,来提示水已经快烧开了。
对上面的程序做个改进:
假设热水器由三部分组成:
热水器,仅仅负责烧水
警报器,发出警报
显示器,显示提示和水温
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace task3
{
public delegate void MyAlarm(int temperature);
public delegate void MyDispaly(int temperature);
class Heater
{
private int temperature;
public int Temperature
{
get { return temperature; }
set
{
if ((temperature >= 0) && (temperature <= 100))
temperature = value;
else
Console.WriteLine("温度有问题!显示出错!");
}
}
public event MyAlarm DoMyAlarm;
public event MyDispaly DoMyDisplay;
public void BoilWater(int m) //m 表示烧水时间,没分钟提高摄氏度
{
Console.WriteLine("感谢您使用热水器,现在温度为{0},
本次烧水时间为{1}分钟。" +
"(每分钟提高10摄氏度)", this.temperature, m);
this.temperature = m * 10 + this.temperature;
if (this.temperature >= 100)
this.temperature = 100;
if (this.temperature >= 95)
{
DoMyAlarm(this.temperature);
DoMyDisplay(this.temperature);
Console.WriteLine("");
}
else
Console.WriteLine("目前还没烧开!
");
}
}
class Alarm
{
public void MakeAlert(int temperature)
{
Console.WriteLine("叮叮叮,叮叮叮。。。
报警器提示水壶水温现在是{0}",temperature);
}
}
class Display
{
public void ShowMsg(int temperature)
{
Console.WriteLine("显示器提示现在的水温为{0}", temperature);
}
}
class Program
{
static void Main(string[] args)
{
Heater he1 = new Heater();
he1.Temperature = 10;
Alarm al1 = new Alarm();
Display di1 = new Display();
he1.DoMyAlarm += al1.MakeAlert;
he1.DoMyDisplay += di1.ShowMsg;
he1.BoilWater(1);
Heater he2 = new Heater();
he2.Temperature = 10;
Alarm al2 = new Alarm();
Display di2 = new Display();
he2.DoMyAlarm += al2.MakeAlert;
he2.DoMyDisplay += di2.ShowMsg;
he2.BoilWater(10);
Console.Read();
}
}
}
运行截图: