本例以猫和老鼠来讲解观察者,首先定义观察者为 老鼠和主人,被观察者为猫,代码如下
public interface Observer {
public void response(Event e);
}
public class Event {
private String name ;
public Event(String name){
this.name = name ;
}
public String getName(){
return name;
}
}
public class Mouse implements Observer {
private String name ;
public Mouse(String name) {
this.name = name ;
}
public void response(Event e) {
System.out.println( name + ":" + e.getName() + " 来了,快跑啊!");
}
}
public class Person implements Observer {
private String name ;
public Person(String name) {
this.name = name ;
}
public void response(Event e) {
System.out.println( name+":"+e.getName() +"你把我吵醒了!");
}
}
public class Cat {
private List<Observer> observers ;
private String name ;
public Cat(String name){
this.name = name;
this.observers = new ArrayList<Observer>();
}
public void call(){
System.out.println(name+":喵...喵...");
for(Observer o:observers){
o.response( new Event(name));
}
}
public void addObserver(Observer observer){
observers.add( observer );
}
public void removeObserver(Observer observer){
observers.remove(observer);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Test {
public static void main(String[] args) {
Cat cat = new Cat("黑猫警长");
cat.addObserver( new Mouse("舒克"));
cat.addObserver( new Mouse("贝塔"));
cat.addObserver( new Person("皮皮鲁"));
cat.call();
}
}