用C#实现:有个高档的热水器,包含一个加热器,一个报警器和一个显示屏,我们给热水器它通上电,当水温超过95度的时候: 1、报警器会开始发出语音,告诉你水的温度; 2、液晶屏也会改变水温的显示,来提示水已经快烧开了。
时间: 2024-03-10 17:50:03 浏览: 19
好的,这是一个简单的实现,下面是C#代码:
```csharp
using System;
class WaterHeater {
private int temperature = 0;
public delegate void BoilHandler(int param);
public event BoilHandler BoilEvent;
public void SetTemperature(int temperature) {
this.temperature = temperature;
Console.WriteLine("水温已经达到了{0}度。", temperature);
if(temperature > 95) {
BoilEvent?.Invoke(temperature);
}
}
}
class Alarm {
public void MakeAlert(int param) {
Console.WriteLine("Alarm:水已经 {0} 度了,快烧开了!", param);
}
}
class Screen {
public void ShowTemperature(int param) {
Console.WriteLine("Screen:水温是 {0} 度。", param);
}
}
class Program {
static void Main(string[] args) {
WaterHeater wh = new WaterHeater();
Alarm alarm = new Alarm();
Screen screen = new Screen();
wh.BoilEvent += alarm.MakeAlert;
wh.BoilEvent += screen.ShowTemperature;
wh.SetTemperature(100);
Console.ReadKey();
}
}
```
这个实现中,水温高于95度时,会触发BoilEvent事件,然后Alarm和Screen类会响应该事件并输出对应的信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)