谁有课程代码?
package dyl.study.observer; import java.util.Observable; public class ConcreteWeatherSubject extends Observable { //天气情况的内容 private String content; public String getContent() { return content; } public void setContent(String content) { this.content = content; this.setChanged(); this.notifyObservers(content); //推方式 } }
package dyl.study.observer; import java.util.Observable; import java.util.Observer; //具体的观察者对象 public class ConcreteObserver implements Observer { private String observerName; @Override public void update(Observable o, Object arg) { //推方式 System.out.println(observerName+"收到了"+arg); //拉方式 System.out.println(observerName+"收到了消息,主动到目标对象那去取得数据,取得的数据为:"+((ConcreteWeatherSubject)o).getContent()); } public String getObserverName() { return observerName; } public void setObserverName(String observerName) { this.observerName = observerName; } }
package dyl.study.observer; public class Client { public static void main(String[] args) { ConcreteWeatherSubject subject = new ConcreteWeatherSubject(); ConcreteObserver p1 = new ConcreteObserver(); ConcreteObserver p2 = new ConcreteObserver(); p1.setObserverName("我"); p2.setObserverName("你"); subject.addObserver(p1); subject.addObserver(p2); subject.setContent("QQ天气:【某地】阴7°/10°,09:05更新~"); } }