RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Using the Observer Pattern to Update Dependent Objects

The Observer pattern defines a one-to-many dependency between objects--when the central object changes state, all its dependents objects are notified and updated automatically. Master this pattern and you won't have to worry about managing consistency of state between components.

any applications need to update their components based on information input coming from a single source. It's often important for these applications to maintain consistency among these components at any given point in time.

Suppose your application needs to maintain consistency between the states of its components or objects with a remote server state that is regularly sending various types of data to your app. Further, your application needs to display the received data in different formats to users through several kinds of components. All of this must be in sync with the data coming in. Since the server sends several different kinds of data, each component is interested in only some of the data. These components may be GUI or non-GUI based.

In this situation, many of your objects' states are dependent on one central object. As this central object changes its state, that change has to propagate to the other dependent objects.

Using pointers or references to update these dependent objects requires you to include header files containing the class definitions of the dependent objects in your central object file. This way, you need to change the central object every time you need to include a new dependent object or exclude an old dependent object. This method is not very efficient and, in some cases, may be impossible.

The Observer Design Pattern
You can solve this complicated problem rather efficiently using the Observer design pattern. This pattern defines a one-to-many dependency between objects so that when the central object changes state, all its dependents objects are notified and updated automatically.

The Observer pattern defines the central object as the Subject and the dependent objects as Observers. Observers subscribe themselves to the Subject, and whenever the Subject's state changes, it notifies the Observers using a consistent interface.

The sample code in this article provides two abstract classes: Subject and Observer. Both provide several pure virtual functions to implement the required interface.

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