Publishing State Changes to Subscribers

One problem that arises in distributed systems is keeping the different elements consistent. When a change occurs in one element, the information must be conveyed to other elements in the system. This capability is required by several architectures that I discuss in this book: Layers (see Chapter 9), Model-View-Controller (see Chapter 13), and Presentation-Abstraction-Control (see Chapter 14).

The Publisher-Subscriber pattern is very similar to the Observer pattern. Figure 21-4 shows the class diagram for Publisher-Subscriber. The interface between the publisher and subscriber can be any IPC mechanisms of your choice, including through the use of messaging-oriented middleware.

images

Figure 21-4: Publisher-Subscriber class diagram.

images

What I'm going to tell you about in this section is a variant on the Observer pattern. Besides changing the class names from ConcreteSubject to Publisher and ConcreteObserver to Subscriber, the biggest difference is that I won't tell you to use an abstract class. This pattern doesn't include the abstract classes, because although abstract classes help decouple the actual publisher and subscriber, they make the resulting code more complex.

This pattern has only two classes: Publisher, which sends notifications, and Subscriber ...

Get Pattern-Oriented Software Architecture For Dummies now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.