Head First Design Patten观察者模式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Head First Design Patten观察者模式相关的知识,希望对你有一定的参考价值。
认识观察者模式
看看报纸和杂志订阅是怎么回事
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; @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; 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); } }
以上是关于Head First Design Patten观察者模式的主要内容,如果未能解决你的问题,请参考以下文章
终于收到了head first design pattern了