现在安卓开发需要用到RxJava Retrofit,而RxJava是观察者模式,于是去看了下观察者模式是怎么个回事。
大概意思应该是 A监视B 但是A并非实时监视B,而是给B注册一个事件,在B发生某种动作(事件)之后通知A,然后A再做出相应的响应。
代码:
ObServer:
package com.example.z.tabview.test.gczms; /** * 抽象观察者 * Created by Z on 2017/6/6. */ public interface ObServer { void update(Subject subject); }
ConcreteObServer:
package com.example.z.tabview.test.gczms; /** * 具体的观察者 * Created by Z on 2017/6/6. */ public class ConcreteObServer implements ObServer { private int state; @Override public void update(Subject subject) { this.state = ((ConcreteSubject) subject).getState(); } public int getState() { return state; } public void setState(int state) { this.state = state; } }
Subject:
package com.example.z.tabview.test.gczms; import java.util.ArrayList; import java.util.List; /** * 抽象主题对象 * Created by Z on 2017/6/6. */ public class Subject { //保存该主题下的所有观察者 protected List<ObServer> listObserver = new ArrayList<>(); public void registerObserver(ObServer obServer) { listObserver.add(obServer); } public void removeObserver(ObServer obServer) { listObserver.remove(obServer); } public void notifyAllObserver() { for (ObServer obServer : listObserver) { obServer.update(this); } } }
ConcreteSubject:
package com.example.z.tabview.test.gczms; /** * 具体主题对象 * Created by Z on 2017/6/6. */ public class ConcreteSubject extends Subject { private int state; public int getState() { return state; } public void setState(int state) { this.state = state; this.notifyAllObserver(); } }
Test:
package com.example.z.tabview.test.gczms; /** * 测试方法 * Created by Z on 2017/6/6. */ public class Test { public static void main(String[] args) { ConcreteSubject cs = new ConcreteSubject(); ConcreteObServer cos1 = new ConcreteObServer(); ConcreteObServer cos2 = new ConcreteObServer(); ConcreteObServer cos3 = new ConcreteObServer(); cos1.setState(10); cos2.setState(20); cos3.setState(30); System.out.println(cos1.getState()); System.out.println(cos2.getState()); System.out.println(cos3.getState()); System.out.println("----------修改后的状态----------"); cs.registerObserver(cos1); cs.registerObserver(cos2); cs.registerObserver(cos3); cs.setState(100); System.out.println(cos1.getState()); System.out.println(cos2.getState()); System.out.println(cos3.getState()); } }
输出:
10
20
30
----------修改后的状态----------
100
100
100