分享

Observer模式

 怀旧妞妞 2010-12-31
开会人(观察者)
public class Person implements Observer{
  String name;
     int changeTimes=0;//记录本人看到的记录更改次数  
     /**
      * 
      */
     public Person(String name) {
         this.name = name;
     }    /*
      * 本人看到了通知
      *
      * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
      */
     public void update(Observable o, Object arg) {
         String first=
         name +"说: 我已经看到了通知," + arg;
         String other=name + "说: 我考!,都该了N次了,N>="+ changeTimes + arg;
         System.out.println(changeTimes==0?first:other);
         changeTimes++;  
       }
}
通知开会人(被观察者)
public class NoticeOfficer extends Observable {
 /**
     * 
     */
    public NoticeOfficer(String content) {       
     this.content = content;
    }    //重要通知
    String content; 
    void sendNotice(List p) {
      for(int i=0;i<p.size();i++){
       Observer  o = (Observer)p.get(i);
       addObserver((Observer) o);
       }
        setChanged();
        notifyObservers(content);
    }  
}
 测试类:
public class Test{
    public static void main(String[] args) {
        NoticeOfficer officer = new NoticeOfficer("今天下午2:60 有会!");
        List personList = new ArrayList();
        personList.add(new Person("校长"));
        personList.add(new Person("流氓"));
        officer.sendNotice(personList);
        officer.content="会议改为3:50";
        officer.sendNotice(personList);
        officer.content="会议改为5:50";
        officer.sendNotice(personList);
    }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多