某企业有一火灾预警中心,火警探测器探测到火情信号后,会自动拨号110火警,并发短信给安全生产负责人和总经理。请利用某设计模式实现此情境,要求画出UML类图,并写出源代码,并测试
时间: 2024-10-12 13:07:11 浏览: 32
这是一个典型的职责链模式(Chain of Responsibility Pattern)的应用场景,因为它涉及到将请求逐级传递给一系列处理者,直到找到能处理该请求的对象。在这个例子中,我们有以下几个角色:
1. 火警检测器(AlarmDetector)作为触发者。
2. 责任链(AlarmHandler)及其一系列子类,如电话报警系统(PhoneAlert),短信报警系统(SMSAlert),以及高级管理层的报警系统(ExecutiveAlert)。
首先,让我们画一个简单的UML类图:
```
+----------------+
| AlarmDetector |
+----------------+
| - handlerChain: AlarmHandler[] |
+----------------+
| + triggerAlarm() | // 触发火警并开始处理
| + addHandler(AlarmHandler) | // 添加新的处理者到链
+----------------+
+----------------+
| AlarmHandler |
+----------------+
| - handler: AlarmHandler | // 下一个处理者
| - performAlarm() | // 处理火警
+----------------+
+----------------+
| PhoneAlert |
+----------------+
| + performAlarm() | // 打电话给110
+----------------+
+----------------+
| SMSAlert |
+----------------+
| + performAlarm() | // 发送短信给负责人和总经理
+--+
| + performAlarm() | // 向高管发送紧急通知
+----------------+
```
接下来,我们可以编写部分源代码示例(Java):
```java
public abstract class AlarmDetector {
private AlarmHandler handlerChain;
public void setHandlerChain(AlarmHandler handlerChain) {
this.handlerChain = handlerChain;
}
public void triggerAlarm() {
handlerChain.performAlarm(this);
}
public abstract void addHandler(AlarmHandler handler);
}
public class AlarmHandler {
private AlarmHandler handler;
public void setHandler(AlarmHandler handler) {
this.handler = handler;
}
public void performAlarm(AlarmDetector detector) {
if (handler != null) {
handler.performAlarm(detector);
} else {
handleAlarm(detector);
}
}
protected abstract void handleAlarm(AlarmDetector detector);
}
// 具体实现
class PhoneAlert extends AlarmHandler {
@Override
protected void handleAlarm(AlarmDetector detector) {
System.out.println("Calling 110");
// 实现打电话的功能
}
}
class SMSAlert extends AlarmHandler {
@Override
protected void handleAlarm(AlarmDetector detector) {
System.out.println("Sending SMS to responsible personnel and CEO");
// 实现发送短信的功能
}
}
class ExecutiveAlert extends AlarmHandler {
@Override
protected void handleAlarm(AlarmDetector detector) {
System.out.println("Notifying executives about the emergency");
// 实现发送高管通知的功能
}
}
```
为了测试这个系统,你可以创建一个`AlarmDetector`实例,添加各个处理者,然后模拟触发火警:
```java
public static void main(String[] args) {
AlarmDetector alarmDetector = new AlarmDetector();
AlarmHandler phoneAlert = new PhoneAlert();
AlarmHandler smsAlert = new SMSAlert();
AlarmHandler executiveAlert = new ExecutiveAlert();
alarmDetector.addHandler(phoneAlert);
alarmDetector.addHandler(smsAlert);
alarmDetector.addHandler(executiveAlert);
alarmDetector.triggerAlarm(); // 测试触发流程
}
```
阅读全文