定义对象间的一种一对多依赖关系,使得每当一个对象改变状态,则其相关依赖的对象都能得到通知并被自动更新.
定义两个接口:
观察者接口(提供更新等操作的方法)
package DesignPattern.ObserverPattern;
public interface AlarmListener {
public void alarm();
}
被观察者接口:(提供注册观察者实现类的方法,提供将改变通知观察者实现类的方法)
package DesignPattern.ObserverPattern;
public interface SensorInterface {
public void register(AlarmListener al);
public void soundTheAlarm();
}
具体被观察者定义:
package DesignPattern.ObserverPattern;
import java.util.Enumeration;
import java.util.Vector;
/**
* 传感器系统
*
*/
public class SensorSystem implements SensorInterface {
Vector v=new Vector();
/**
* 注册监听者
*/
public void register(AlarmListener al) {
v.addElement(al);
}
/**
* 发送告警
*/
public void soundTheAlarm() {
Enumeration e=v.elements();
while(e.hasMoreElements()){
AlarmListener al=null;
al=(AlarmListener)e.nextElement();
al.alarm();
}
} }
观察者实现类:
package DesignPattern.ObserverPattern;
public class AutoDefense implements AlarmListener{
public void alarm() {
System.out.println("********发现威胁*******");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(" 开始启动自动防御系统......");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("********检测到入侵源是一队恐怖分子*****");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package DesignPattern.ObserverPattern;
public class Gun implements AlarmListener {
public void alarm() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("武器瞄准中......");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("***开枪***");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("恐怖分子已经全部击毙");
}}
测试类:
package DesignPattern.ObserverPattern;
import DesignPattern.ObserverPattern.AlarmListener;
import DesignPattern.ObserverPattern.SensorSystem;
import DesignPattern.ObserverPattern.SensorInterface;;
public class ClientTest {
public static void main(String[] args){
SensorInterface sensor=new SensorSystem();
sensor.register(new AutoDefense());
sensor.register(new Gun());
sensor.soundTheAlarm();
}
}