[设计模式]NetworkManagementService中的观察者模式
观察者模式
观察者模式有如下角色
(1)被观察者(Subject)
(2)观察者(Observer)
public class Subject{ private: list<Observer> mObservers; protect: void onChange(){ for(int i=0; i<mObservers.size(); ++i){ mObservers.get(i).onAction(); } } public: void attach(Observer m){ mObservers.add(m); } void detach(Observer m){ mObservers.remove(m); } }; public class Observer{ public: virtual void onAction(); }; public ConcreteSubject extends Subject { private: int content = 0; public: void updateContent(int n){ content = n; onChange(); } int getContent(){ return content; } }; public ConcreteObserver extends Observer{ private: ConcreteSubject mConreteSubject; public: ConcreteObserver(ConcreteSubject subject){ mConcreteSubject = subject; } void onAction(){ int content = mConcreteSubject.getcontent(); } };
如下为NetworkManagementService中的注册观察者的函数(regisrterObserver)和通知观察者的函数(notifyInterfaceStatusChanged),其实在NetworkManagementService中还有很多类型的通知函数,通知变动的内容如下:
InterfaceStatus
InterfaceLinkState
InterfaceAdded
InterfaceRemoved
LimitReached
InterfaceClassActivity
在NetworkManagementService中观察者是INetworkManagementEventObserver类型,在INetworkManagementEventObserver.aidl
NetworkManagementService中的观察者模式则更为简单,如下:
观察者与被观察者的子类之间没有相互依赖关系。如果加上mDataActivityObserver 的幕后操纵者ConnectivityService,结构如下:
其实在ConnectivityService中除了mDataActivityObserver作为观察者,还有mTethering也作为观察者注册到NetworkManagemanetService中。
此外除了ConnectivityService还有NetworkPolicyManagerService也有向NetworkMangementService派遣观察者。这种设计真的太妙了。
(版权所有,转载请告知)