Design Pattern: Publisher-Subscriber

 

 

Intention

Keep components synchronized

Inter-component communication

Multiple component usage

The Publisher-Subscriber design pattern helps to keep the state of cooperating components synchronized. To achieve this it enables one-way propagation of changes: one publisher notifies any number os subscribers about changes of its state

 

 

Aka

Observer, Dependents

Consumers, Producers (Anyone ?)

 

 

Problem

Data is centrialized but many (remote) components depend on this data

Forces:

One or more components must be notified about state changes in a particular component

The number and IDs of dependent components are known only in run time

Explicit polling by dependents of new information is not feasible

Components should not be tightly coupled when introducing a change-propagation mechanism

 

 

Solution and Dynamic

Publisher is the main role

All components dependent on changes in the publisher are its subscribers

Publisher maintains a registry of currently-subscribed components

Subscribers use the interface offered by the publisher

Whenever the publisher changes state, it sends a notification to all its subscribers

The subscribers in turn retrieve the changed data at their discretion

 

 

Implementation

Define an interface between publisher and subscriber (by using an abstract class or Java interface)

Implement Publisher

Implement Subscriber

 

Implementation Notes

Introduce abstract base classes to let different classes be publishers or subscribers

The publisher can decide when internal state changes it will notify its publishers about. It may also queue several changes before calling notify()

An object can be a subscriber to many publishers

An object can take both roles, that of a publisher as well as subscriber

Notification can be differentiated according to event type

Publisher can send selected details data changes to different subscribers depending on subscriber levels

Push model: publishers just send all the info to subscribers, subscribers have not choice on when to receive notification

Pull model: publishers only send "data are here" messages and subscribers will pull the data down when ready

 

 

Variants

Gatekeeper: apply to distributed system (one or two processes publishers)

Event Channel: OMG in its Event Service Specification - strong decoupled publishers and subscribers

publisher - proxy publisher - | - proxy subscriber - event channel - proxy publisher - | - proxy subscriber - subscriber

 

 

Conseqences

Advantages

Changability

Extensibility

Support distributed system

Disadvantages

Efficiency

Complexity