package cn.my.demo; //设计一个监听器 public class Demo2 { public static void main(String[] args) { Person p=new Person(1001,"张三"); p.refisterListener(new PersonListener() { public void dorun(Event e) { Person p=e.getSource(); System.out.println("Who is in front of people to have a meal, that is "+p.getName()); } public void doeat(Event e) { Person p=e.getSource(); System.out.println("Who in the previous run, that is "+p.getName()); } }); p.eat(); p.run(); } } //观察者设计模式 class Person{ private Integer id ; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Person(Integer id ,String name) { this.id=id; this.name=name; } //这个就是一个事件源 private PersonListener listener; public void eat(){ if(listener!=null){ listener.doeat(new Event(this)); } System.out.println("this is eat!"); } public void run(){ if(listener!=null){ listener.dorun(new Event(this)); } System.out.println("this is run!"); } public void refisterListener(PersonListener listener){ this.listener=listener; } } //事件监听器 interface PersonListener{ public void doeat(Event e); public void dorun(Event e); } //这个是事件对象 class Event{ //事件对象 需要封装事件源对象 private Person source; public Person getSource() { return source; } public Event(Person source) { super(); this.source = source; } public Event() { super(); } public void setSource(Person source) { this.source = source; } }