拉模式的观察者
主题Subject接口
public interface Subject { public void registerObesrver(Observer observer); public void removeObeserver(Observer observer); public void notifyObeservers(); }
天气数据
public class WeatherData implements Subject { private Double temperate = null; // ArrayList默认容量为10,当大量添加observers,可能存在性能问题 private List<Observer> observers = new ArrayList<>(); public Double getTemperate() { return temperate; } public void setTemperate(Double temperate) { this.temperate = temperate; notifyObeservers(); } @Override public void registerObesrver(Observer observer) { observers.add(observer); } @Override public void removeObeserver(Observer observer) { observers.remove(observer); } @Override public void notifyObeservers() { for (Observer observer : observers) { observer.update(); } } }
观察者Observer
public interface Observer { public void update(); }
tv观察者
public class TvOberser implements Observer { private WeatherData weatherData; public TvOberser(WeatherData weatherData) { this.weatherData = weatherData; weatherData.registerObesrver(this); } @Override public void update() { System.out.println("**************************"); System.out.println("********* TV ***********"); System.out.println("temperate:" + weatherData.getTemperate()); System.out.println("**************************"); } }
Radio观察者
public class RadioObserver implements Observer { public WeatherData weatherData; public RadioObserver(WeatherData weatherData) { this.weatherData = weatherData; weatherData.registerObesrver(this); } @Override public void update() { System.out.println("-----------------------------"); System.out.println("--------- Radio -----------"); System.out.println("temperate:" + weatherData.getTemperate()); System.out.println("-----------------------------"); } }
测试类
public class Main { public static void main(String args[]) { WeatherData weatherData = new WeatherData(); TvOberser tvOberser = new TvOberser(weatherData); RadioObserver radioObserver = new RadioObserver(weatherData); weatherData.setTemperate(100.0); weatherData.setTemperate(99.0); weatherData.setTemperate(98.0); weatherData.setTemperate(96.0); } }
推模式后续更新----------
原文:https://www.cnblogs.com/lz-0011/p/11674513.html