Browse DevX
Sign up for e-mail newsletters from DevX


Synchronize Data Among Objects with the Publish/Subscribe Design Pattern

Use the Publish/Subscribe design pattern to propagate changes to data between objects in your application.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

pplications often need to propagate changes to data to synchronize the state of objects in an application, particularly in user-interface applications where multiple windows can reference the same data. In this type of application, changes to elements of the underlying information must be reflected in all the windows containing references to it.

Take, for example, an application that manages information about people. Multiple windows containing the name of a person might be open at once. If you change the person's name in one window and save, you would expect the name to immediately change in all other windows as well. You can accomplish this functionality by leveraging a design pattern known as Publish/Subscribe. This design pattern is a variation of the Observer pattern (see Figure 1) described in Design Patterns, Elements of Reusable Object Oriented Software, a work many consider the original design patterns book. In the Observer pattern, an object (the Observer) registers to listen for events from another object (the Subject); the Observer is implicitly aware of the Subject.

Figure 1 | Click here to get a close-up view of the Observer Pattern.

The Publish/Subscribe (see Figure 2) variation of this pattern introduces the Event Channel, a layer of separation between the Subject and the Observer. This layer removes the binding between the Observer and the Subject and creates a loosely coupled relationship between the two.
Figure 2 | Click here to get a close-up view of the Publish/Subscribe Pattern.

The Event Channel can be described as a messaging center that routes events. The Publisher (know in the Observer pattern as the Subject) publishes events to the Event Channel. The Event Channel is responsible for disseminating the events to all of the Subscribers (know in the Observer pattern as the Observer). An application may contain one or more Event Channels, each disseminating different types of events to interested Subscribers. Also, whereas in Observer the events come only from a specific source, in Publish/Subscribe any object that is aware of the Event Channel may publish an event.

This architecture removes the dependency between the Observer and Subject, resulting in a more generic design for your application. Also, by requiring no direct relationship between the Publisher and the Subscriber, it increases the maintainability of your application.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date