觀察者模式

/**
 * 觀察者
 * 裏面有一個方法,用來監視Person的run方法
 */
public interface PersonListener {
   public void running(PersonEvent e);

/*
 * 觀察者方法的參數,能夠得到被觀察者對象
 */
public class PersonEvent{
   private Object src;
   public PersonEvent(Object o){
  this.src=o;
   }
   public Object getSource(){
  return src;
   }
}

/**
 * 這是一個觀察者模式的示例,Person是被觀察者,持有一個觀察者對象
 * 在調用監聽方法addPersonListener時,把觀察者傳入
 */
public class Person {
    private PersonListener pl;
    public void addPersonListener(PersonListener pl){
    this.pl=pl;
    };
    /**
     * 在run()中回調PersonListener的running方法
     */
    public void run(){
    if(pl!=null){
    pl.running(new PersonEvent(this));
    }
    System.out.println("I'm running now");
    }
}

/**
 * 這是一個測試類
 *
 */
public class ObserveDemo {
public static void main(String[] args) {
         Person p=new Person();
         System.out.println(p.hashCode());
        
         p.addPersonListener(new PersonListener(){
public void running(PersonEvent e) {
System.out.println("Are you really runing now ,OMG!");
System.out.println(e.getSource().hashCode());
}
         
         });
         p.run();
}
}
相關文章
相關標籤/搜索