自己动手实现RxJava。
最简单的观察者模式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Data {}interface Subscriber { public void onEvent (Data d) ; } class Observable { private Subscriber subscriber; public void register (Subscriber s) { subscriber = s; } private void onEvent (Data d) { if (subscriber != null ) { subscriber.onEvent(d); } } }
多级观察者 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 class InterSubscriber implements Subscriber { private Subscriber subscriber; public InterSubscriber register (Subscriber s) { subscriber = s; } @Override public void onEvent () { if (subscriber != null ) { subscriber.onEvent(); } } } Observable o = new Observable(); InterSubscriber is0 = new InterSubscriber(); InterSubscriber is1 = new InterSubscriber(); Subscriber s = new Subscriber(); o.register(is0); is0.register(is1); is1.register(s); o.onEvent();
数据处理流程: o.onEvent() -> is0.onEvent() -> is1.onEvent() -> s.onEvent
中间观察者的另一面是被观察者 被观察者的行为可以总结为:
产生事件,事件