观察者模式
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);
}
}
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+"\n");
}
public String getObserverName() {
return observerName;
}
public void setObserverName(String observerName) {
this.observerName = observerName;
}
}
public static void main(String[] args) {
ConcreteWeatherSubject subject = new ConcreteWeatherSubject();
ConcreteObserver girl = new ConcreteObserver();
ConcreteObserver boy = new ConcreteObserver();
girl.setObserverName("女孩");
boy.setObserverName("男孩");
subject.addObserver(girl);
subject.addObserver(boy);
subject.setContent("明天也会下雨");
}
![这里写图片描述](https://img-blog.csdn.net/20170414193128606?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY29kZXN1cGVyTWFuMTMxNA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)