肖恩画家:Observer模式
来源:百度文库 编辑:九乡新闻网 时间:2024/04/27 14:14:13
开会人(观察者)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 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);
}
}
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
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);
}
}