某公司欲开发一套机房监控系统,如果机房达到某一指定温度,传感器将作出反应,将信号传递给响应设备,如警示灯将闪烁、报警器将发出报警、安全逃生门将自动开启、隔热门将自动关闭等,每一种响应设备的行为由专门的程序来控制,采用观察者模式来设计该系统。
public interface AlarmListener {
public void doSomeThing();
}
public class InsulatedDoor implements AlarmListener{
public void doSomeThing(){
close();
}
public void close(){
System.out.println("隔热门将自动关闭");
}
}
public class Light implements AlarmListener{
public void doSomeThing(){
light();
}
public void light(){
System.out.println("警示灯闪烁");
}
}
public class Security implements AlarmListener{
@Override
public void doSomeThing() {
open();
}
public void open(){
System.out.println("安全逃生门即将自动开启");
}
}
import java.util.ArrayList;
public class Sensor {
private double tem;
private ArrayList<AlarmListener> alarmListeners = new ArrayList<AlarmListener>();
public void add(AlarmListener listener){
this.alarmListeners.add(listener);
}
public void remove(AlarmListener listener){
this.alarmListeners.remove(listener);
}
public void testAlarm(){
for(AlarmListener obj : alarmListeners){
obj.doSomeThing();
}
}
public void setTem(double tem) {
this.tem = tem;
}
public void sendMessage(){
if(this.tem>40.0){
testAlarm();
}else{
System.out.println("正常工作");
}
}
}
public class Voice implements AlarmListener{
@Override
public void doSomeThing() {
alarm();
}
public void alarm(){
System.out.println("报警器在报警");
}
}