package cn.lfd.observer;
//被观察者
public class Person {
private PersonListener personListener;
public void eat() {//被观察者行为
System.out.println("我在吃");
if(personListener!=null) {
personListener.doeat(new Event(this));//被观察者发生行为时,观察者会做出响应
}
}
public void sleep() {
System.out.println("我在睡觉");
if(personListener!=null) {
personListener.dosleep(new Event(this));
}
}
public void addListenner(PersonListener personListener) {//提供一个方法接收一个观察者的观察
this.personListener = personListener;
}
}
//成为观察者需要实现的接口
interface PersonListener {
public void doeat(Event e);
public void dosleep(Event e);
}
//发生的事件,通过事件可以得到被观察者
class Event {
private Person sourse;
public Event(Person sourse) {
super();
this.sourse = sourse;
}
public Person getSourse() {
return sourse;
}
public void setSourse(Person sourse) {
this.sourse = sourse;
}
}
测试代码:
package cn.lfd.observer;
public class TestPerson {
public static void main(String[] args) {
Person p = new Person();//创建一个被观察者
p.addListenner(new PersonListener() {//为被观察者添加一个观察者
public void dosleep(Event e) {//观察者对被观察者的行为应该作出什么反应
System.out.println("吃死你");
}
public void doeat(Event e) {
System.out.println("睡死你");
}
});
p.eat();//被观察者发生行为
p.sleep();
}
}
小提示:
java设计模式来源于生活,感到困惑时,不妨想一想生活中的事例,或许你会体会到柳暗花明又一村的喜悦。