认识观察者模式
看看报纸和杂志订阅是怎么回事
1、报社的业务是出版报纸
2、你向报社订阅报纸
3、你不想继续看该报纸时,取消订阅该报社的报纸
4、报社在新出版报纸时,分发报纸给订阅者
出版者 + 订阅者 = 观察者
观察者模式定义了对象间一对多依赖,当一个对象状态改变时,它的依赖者都会收到通知并自动更新,主题一般有状态,而且能够控制状态
public interface Subject { public void registerObserver(Observer o); public void removeObserver(Observer o); public void notifyObserver(); } public interface Observer { public void update(float a,float b,float c); } public interface DisplayElement { public void display(); } public class WeatherData implements Subject { private ArrayList<Observer> observers; private float t; private float h; private float p; public WeatherData(){ observers = new ArrayList<Observer>(); } @Override public void notifyObserver() { for (int i=0;i<observers.size();i++){ Observer observer = observers.get(i); observer.update(t,h,p); } } @Override public void registerObserver(Observer o) { observers.add(o); } @Override public void removeObserver(Observer o) { int i = observers.indexOf(o); if(i>0) { observers.remove(i); } } public void measurementChanged(){ notifyObserver(); } public void setMeasurements(float t,float h,float p){ this.t = t; this.h = h; this.p = p; measurementChanged(); } } public class CurrentConditionsDisplay implements Observer,DisplayElement{ private float t; private float h; private float p; private Subject subject; public CurrentConditionsDisplay(Subject subject){ this.subject = subject; subject.registerObserver(this); } @Override public void display() { System.out.println("T : " +t +" H : "+h + " P : "+p); } @Override public void update(float a, float b, float c) { this.t = a; this.h = b; this.p = c; System.out.println(a); System.out.println(b); System.out.println(c); display(); } } public class WeatherStation { public static void main(String[] args){ WeatherData wd = new WeatherData(); CurrentConditionsDisplay ccd1 = new CurrentConditionsDisplay(wd); CurrentConditionsDisplay ccd2 = new CurrentConditionsDisplay(wd); wd.setMeasurements(1,2,3); wd.setMeasurements(4,5,6); } }
时间: 2024-12-24 06:56:16