Chaining of observer/observable pattern

亡梦爱人 提交于 2019-12-12 16:25:39

问题


Is there a design pattern that forms a "composite" observer/observable?
I mean I have an observable A that notifies its listeners on some change.
Each listener is also an observable and notifies its own listener (on some action it did which action was triggered by notification of the first observable).
Is this "chaining" of observers/observables ok as design or is there a standard pattern for this?


回答1:


For the chaining you mentioned, I don't see any difference.

The aim of Observer pattern is, when the state of an object is changed, it notify interested parties (listener/observer) about the change and let the listener react according to the state change.

If the state change of the listener is, by design, observed by other interested parties, I don't see any reason why I can't use observer pattern for the publishing the event.

However it is simply another observer-observable relationship. There is no special "chaining" happening.

A bit OT: something that is more appropriate to be called chaining is: An observed object O send an event E to listener A, and A will propagate the event to another listener B. However logically they are all listening to event originated from O. Such kind of "chaining" you can be done by using decorator pattern.




回答2:


Your classes should implement both interfaces: observer and subject. Challange is registering all observers to proper objects.
All you need is to add notifyObservers() in notify() method in Observer classes (link to wiki).
Note you can start infinite loop of notifications: A => B => C => A => ... and so on.



来源:https://stackoverflow.com/questions/15107684/chaining-of-observer-observable-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!