public class Demo { public static void main(String[] args) { //聲明一個觀察者 Person p = new Person(); //添加觀察者方法 p.addPersonLister(new PersonLister() { @Override public void runing(PersonEvent e) { System.err.println(e.getSource()); } }); //調用方法 p.say(); } } //被觀察者 class Person{ private PersonLister pl; public void addPersonLister(PersonLister pls){ this.pl = pls; } public void say(){ if(pl != null){ pl.runing(new PersonEvent(this)); } } } //觀察者 interface PersonLister{ public void runing(PersonEvent e); } //觀察者事件 class PersonEvent{ private Object obj; public PersonEvent (Object objs){ this.obj = objs; } public Object getSource(){ return obj; } }