分类: Java
2011-06-01 21:17:17
}
package com.bbsoft.observer.javaUtil.test;
import java.util.Observable;
import java.util.Observer;
public class Subscriber implements Observer {
private Observable observer;
private String subscriberName;
private String magazineName;
private String publishDate;
Subscriber(Observable observer, String subscriberName) {
this.observer = observer;
this.subscriberName = subscriberName;
this.observer.addObserver(this);
}
public void update(Observable o, Object arg) {
if (o instanceof PostOffice) {
String[] publishInfo = (String[]) arg;
magazineName = publishInfo[0];
publishDate = publishInfo[1];
display();
}
}
public void display() {
System.out.println("subscriber Name: " + subscriberName);
System.out.println("magazine Name: " + magazineName);
System.out.println("publish Date: " + publishDate);
System.out.println("------------------------------");
}
}
测试类:
package com.bbsoft.observer.javaUtil.test;
public class TestJavaUtilObserver {
public static void main(String[] args) {
PostOffice post = new PostOffice();
Subscriber tim = new Subscriber(post, "tim");
Subscriber mike = new Subscriber(post, "mike");
post.publishMagazine("advanced", "2009-6-30");
post.deleteObserver(mike);
post.publishMagazine("haha", "2009-6-30");
}
}