Several times, I’ve found myself in a situation where I want to add functionality to an existing Observer
–Observable
relationship.
For example, let’s say I have an Observable
class called PriceFeed
, instances of which are created by a variety of PriceSources
. Observers
on this are notified whenever the underlying PriceSource
updates the PriceFeed
with a new price.
Now I want to add a feature that allows a (temporary) override to be set on the PriceFeed
. The PriceSource
should still update prices on the PriceFeed
, but for as long as the override is set, whenever a consumer asks PriceFeed
for it’s current value, it should get the override.
The way I did this was to introduce a new OverrideablePriceFeed
that is itself both an Observer
and an Observable
, and that decorates the actual PriceFeed
. It’s implementation of .getPrice()
is straight from Chain of Responsibility, but how about the handling of Observable events? When an override is set or cleared, it should issue it’s own event to Observers
, as well as forwarding events from the underlying PriceFeed
.
I think of this as some kind of a chained observer, and was curious if there’s a more definitive description of a similar pattern.
10
That’s called Reactive Programming.
Look at Rx.
Rx is all about this.
It treats observables as enumerables and then what you are doing becomes as simple as calling map on the first sequence of events.
events.map(new function(each) { return override != null ? override : each }
Rx is available for many languages, you’ll find a video with an introduction of RxJS for Javascript here, http://youtu.be/FqBq4uoiG0M
Sounds like what you’re looking for is an interceptor. You can have your PriceFeed
pass its list of observers to a new PriceFeedInterceptor
that watches the PriceFeed
and passes on either the regular or overridden price as appropriate. Your observers shouldn’t need to be changed, but the PriceFeed
will have to know about the interceptor and be prepared to delegate to it.