被观察者的父类接口:
public interface BeiObservable {
public void addObserver(Observer o);
public void deleteObserver(Observer o);
public void notifyObservers(String context);
}
观察者的父类接口:
public interface Observer {
public void update(String context);
}
被观察者的具体实现类,韩非子:
public class HanFeiZi implements BeiObservable {
private ArrayList<Observer> observerList = new ArrayList<Observer>();
@Override
public void addObserver(Observer o) {
this.observerList.add(o);
}
@Override
public void deleteObserver(Observer o) {
this.observerList.remove(o);
}
@Override
public void notifyObservers(String context) {
for (Observer o : observerList) {
o.update(context);
}
}
// 韩非子要吃饭了
public void haveBreakfast() {
System.out.println("韩非子:开始吃饭了..."); // 通知所有的观察者
this.notifyObservers("韩非子在吃饭");
}
// 韩非子开始娱乐了,古代人没啥娱乐,你能想到的就那么多
public void haveFun() {
System.out.println("韩非子:开始娱乐了...");
this.notifyObservers("韩非子在娱乐");
}
}
观察者的具体实现类,李斯:
public class LiSi implements Observer {
@Override
public void update(String context) {
System.out.println("李斯:观察到韩非子活动,开始向老板汇报了...");
this.reportToQinShiHuang(context);
System.out.println("李斯:汇报完毕,秦老板赏给两个萝卜吃吃...\n");
}
private void reportToQinShiHuang(String reportContext) {
System.out.println("李斯:报告,秦老板!韩非子有活动了---》" + reportContext);
}
}
观察者的具体实现类,王思:
public class WangSi implements Observer {
@Override
public void update(String context) {
System.out.println("王斯:观察到韩非子活动,开始向老板汇报了...");
this.reportToQinShiHuang(context);
System.out.println("王斯:汇报完毕,秦老板赏给两个萝卜吃吃...\n");
}
private void reportToQinShiHuang(String reportContext) {
System.out.println("王斯:报告,秦老板!韩非子有活动了---》" + reportContext);
}
}
客户端:
public class Client {
public static void main(String[] args) throws InterruptedException{
Observer liSi = new LiSi();
Observer wangSi = new WangSi();
HanFeiZi hanFeiZi = new HanFeiZi();
hanFeiZi.addObserver(liSi);
hanFeiZi.addObserver(wangSi);
hanFeiZi.haveBreakfast();
}
}