//设计一个事件源,被监听器监听,观察者设计模式
public class Demo1 {
public static void main(String[] args) {
Person person = new Person();
person.registerListener(new PersonListener() {
public void dorun(Event e) {
Person person = e.getSource();
System.out.println(person + " 跑死你");
}
public void doeat(Event e) {
Person person = e.getSource();
System.out.println(person + " 吃死你");
}
});
person.eat();
}
}
class Person{
private PersonListener listener;
public void eat(){
if(listener != null){
listener.doeat(new Event(this));
}
}
public void run() {
if(listener != null){
listener.dorun(new Event(this));
}
}
public void registerListener(PersonListener listener){
this.listener = listener;
}
}
interface PersonListener{
public void doeat(Event e);
public void dorun(Event e);
}
class Event{
private Person source;
public Event() {
super();
}
public Event(Person source) {
super();
this.source = source;
}
public Person getSource() {
return source;
}
public void setSource(Person source) {
this.source = source;
}
}
观察者模式的一个示例
最新推荐文章于 2023-11-02 10:45:42 发布