Is it correct from a design point of view to make an object both an Observer and Observable at the same time?

Michael Wax

Yes, and this can be the preferred pattern in some cases.

For example, suppose you were writing a supply chain management system for a retail chain. Each store object in your system generates item-sold events; when the chain generates enough of these for a particular product, a buyer object generates a purchase order for more of the product. However, the buyer object has no particular interest in individual item sold events. Instead, the buyer (Observer) registers to receive out-of-stock events from the warehouse (Observable); the warehouse, as Observer, registers with the individual stores (Observables) to receive item-sold events. Thus, the warehouse is both Observer and Observable. (Please note that this is a synthetic example, and probably not the way to organize a supply chain.)

Another reason to use one or more central Observer-Observable object in between ultimate Observers and Observables is to fully decouple the two. In some cases, Observer and Observable may exist on different machines, and may rely on the central Observer-Observable to hide this complication.

A good source for more details is the Publisher-Subscriber section of Buschmann et al., Pattern-Oriented Software Architecture: A System of Patterns.

About | Sitemap | Contact