Introduction to the Observer Pattern
Introduction to the Observer Pattern
Welcome back! We're continuing our exploration of Behavioral Patterns. In this lesson, we will delve into the Observer Pattern, another fundamental pattern that emphasizes object communication and responsibility distribution. This pattern allows an object, known as the subject, to maintain a list of its dependents, called observers, and notify them automatically of any state changes, usually by calling one of their methods.
Previously, we looked at the Command Pattern, which encapsulates a request as an object. Now, let's build on that knowledge and explore how the Observer Pattern facilitates communication between objects in a seamless and efficient manner.
Core Components of the Observer Pattern
In this lesson, you will learn how to implement the Observer Pattern by understanding its main components and their roles. The Observer Pattern typically involves a Subject, Observer, Concrete Observer, and Client.
We'll start by defining the Observer class that lays out the interface for receiving updates.
In this code snippet, the Subscriber class defines the update method. This method will be called by the subject to notify subscribers of any updates.
Next, we need to create the NewsPublisher class, which acts as the Subject. This class maintains a list of subscribers and provides methods to add and remove subscribers, as well as to notify them.
The NewsPublisher class has three methods: add_subscriber to add a new subscriber, remove_subscriber to remove an existing subscriber, and publish to notify all subscribers of new news.
Now, let's implement a concrete observer, which in this case will be a specific type of subscriber. This observer will define how to handle the updates received from the subject.
The ConcreteSubscriber class extends the Subscriber base class and implements the update method to print the news received.
Finally, let's see how these components work together in the main function, which serves as the client in this pattern.
In the main function, we first create an instance of NewsPublisher and two ConcreteSubscriber objects. We then add the subscribers to the publisher, publish some news, remove one subscriber, and publish another piece of news to see how the system reacts to these state changes.
