/**
* 观察者
* 里面有一个方法,用来监视Person的run方法
*/
public interface PersonListener {
public void running(PersonEvent e);
}
/*
* 观察者方法的参数,可以获得被观察者对象
*/
public class PersonEvent{
private Object src;
public PersonEvent(Object o){
this.src=o;
}
public Object getSource(){
return src;
}
}
/**
* 这是一个观察者模式的示例,Person是被观察者,持有一个观察者对象
* 在调用监听方法addPersonListener时,把观察者传入
*/
public class Person {
private PersonListener pl;
public void addPersonListener(PersonListener pl){
this.pl=pl;
};
/**
* 在run()中回调PersonListener的running方法
*/
public void run(){
if(pl!=null){
pl.running(new PersonEvent(this));
}
System.out.println("I'm running now");
}
}
/**
* 这是一个测试类
*
*/
public class ObserveDemo {
public static void main(String[] args) {
Person p=new Person();
System.out.println(p.hashCode());
p.addPersonListener(new PersonListener(){
public void running(PersonEvent e) {
System.out.println("Are you really runing now ,OMG!");
System.out.println(e.getSource().hashCode());
}
});
p.run();
}
}