观察者模式
- 对象之间==多对一依赖==的一种设计模式,被依赖对象为subject,依赖对象为observer,subject通知observer变化,气象站通知网站数据变化.
- 推送和获取
- 用户向站点注册.站点通知所有用户取,或者站点推送
- 无法在运行时动态添加第三方
- 违反oop原则
- 在weather中,当增加一个第三方时,都需要创建一个对应的第三方公告板对象,并加入到datachange()中去,不利于维护,也不是动态加入
//传统示例
main(){
new Weather(new CurrentCondition).setdata(11f,12f,13f);
}
public class CurrentCondition {
//温度,气压,湿度
private float temperature;
private float pressure;
private float humidity;
//更新天气信息,使用推送模式
public void update(float temperature,float pressure,float humidity) {
this.temperature=temperature;
this.pressure=pressure;
this.humidity=humidity;
display();
}
public void display() {
System.out.println(temperature+pressure+humidity);
}
}
public class Weather {
float temperature;
float pressure;
float humidity;
CurrentCondition currentCondition;
public Weather(float temperature, float pressure, float humidity, CurrentCondition currentCondition) {
this.temperature = temperature;
this.pressure = pressure;
this.humidity = humidity;
this.currentCondition = currentCondition;
}
//当有数据更新时,调用
public void setData(float temperature,float pressure,float humidity) {
this.temperature = temperature;
this.pressure = pressure;
this.humidity = humidity;
//将最新信息推送出去
dataChange();
}
public void dataChange() {
currentCondition.update(temperature,pressure,humidity);
}
//getterandsetter()
}
使用观察者模式改进
main(){
new Weather();
new CurrentCondition();
weather.registerObserver(currentCondition);
weather.setdata(11f,12f,13f);
}
public interface subject{
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyall();
}
public interface Observer{
public update(float temp,float pressure,float huminity);
}
public class CurrentCondition implements Observer{
//温度,气压,湿度
private float temperature;
private float pressure;
private float humidity;
//更新天气信息,使用推送模式
public void update(float temperature,float pressure,float humidity) {
this.temperature=temperature;
this.pressure=pressure;
this.humidity=humidity;
display();
}
public void display() {
System.out.println(temperature+pressure+humidity);
}
}
public class Weather implements Subject{
float temperature;
float pressure;
float humidity;
ArrayList<Observer> observers;
public Weather(float temperature, float pressure, float humidity, CurrentCondition currentCondition) {
this.temperature = temperature;
this.pressure = pressure;
this.humidity = humidity;
this.currentCondition = currentCondition;
}
//当有数据更新时,调用
public void setData(float temperature,float pressure,float humidity) {
this.temperature = temperature;
this.pressure = pressure;
this.humidity = humidity;
//将最新信息推送出去
dataChange();
}
public void registerObserver(Observer o){
observers.add(o);
}
public void removeObserver(Observer o){
observers.remove(o);
}
public void dataChange(){
notifyall();
}
public void notifyall(){
observers.for(i){
observers.get(i).update(this.temp,this.pressure,this.huminity);
}
}
//getterandsetter()
}