设计模式-观察者模式
基本介绍
- 对象之间多对一依赖的一种设计方案,被依赖的对象为Subject。依赖的对象为Observer,Subject通知Observer变化
代码实现
- 通过观察者模式实现发布天气数据的功能,主要是通过将观察者聚合在Subject,当Subject改变的时候进行调用每一个观察者
//接口,让WeatherData来实现
public interface Subject {
void registerObserver(Observer o);
void removeObserver(Observer o);
void notiyObserver();
}
//天气数据
public class WeatherData implements Subject {
private List<Observer> observers;
private float temperatrue;
private float pressure;
private float humidity;
public float getTemperatrue() {
return temperatrue;
}
public void setTemperatrue(float temperatrue) {
this.temperatrue = temperatrue;
}
public float getPressure() {
return pressure;
}
public void setPressure(float pressure) {
this.pressure = pressure;
}
public float getHumidity() {
return humidity;
}
public void setHumidity(float humidity) {
this.humidity = humidity;
}
public WeatherData() {
observers = new ArrayList<>();
}
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
@Override
public void removeObserver(Observer o) {
observers.remove(o);
}
@Override
public void notiyObserver() {
observers.forEach(e -> e.updaet(temperatrue, pressure, humidity));
}
public void setData(float temperatrue, float pressure, float humidity) {
this.temperatrue = temperatrue;
this.pressure = pressure;
this.humidity = humidity;
dataChange();
}
public void dataChange() {
notiyObserver();
}
}
//观察者接口
public interface Observer {
void updaet(float temperatrue, float pressure, float humidity);
}
public class Baidu implements Observer{
private float temperatrue;
private float pressure;
private float humidity;
@Override
public void updaet(float temperatrue, float pressure, float humidity) {
this.temperatrue = temperatrue;
this.pressure = pressure;
this.humidity = humidity;
display();
}
public void display() {
System.out.println("==============baidu===============");
System.out.println(temperatrue);
System.out.println(pressure);
System.out.println(humidity);
}
}
public class CurrentConditions implements Observer{
private float temperatrue;
private float pressure;
private float humidity;
@Override
public void updaet(float temperatrue, float pressure, float humidity) {
this.temperatrue = temperatrue;
this.pressure = pressure;
this.humidity = humidity;
display();
}
public void display() {
System.out.println("==============CurrentConditions===============");
System.out.println(temperatrue);
System.out.println(pressure);
System.out.println(humidity);
}
}
//客户端
public class Client {
public static void main(String[] args) {
WeatherData weatherData = new WeatherData();
weatherData.registerObserver(new CurrentConditions());
weatherData.registerObserver(new Baidu());
weatherData.setData(10, 20, 30);
}
}