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.

Figure 21-4: Publisher-Subscriber class diagram.

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access