開會人(觀察者)
public class Person implements Observer{
String name; int changeTimes=0;//記錄本人看到的記錄更改次數(shù) /** * */ 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 +"說: 我已經(jīng)看到了通知," + 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); } } |
|
來自: 懷舊妞妞 > 《設(shè)計模式》