The observer pattern belongs to the behavior pattern, which focuses on the communication between objects. The observer pattern applies to a one-to-many relationship of objects, where multiple objects rely on a single object. When the state of the object changes, other objects can receive corresponding notifications.
A common observer pattern is the publish-subscribe model, where the observers subscribe to a subject, and the subject publishes notification to the observers when its status changes.
Here we have an abstract class Observer, and three classes that inherit from it. These classes override the handle() method which handles messages according to their IDs. Observer1 handles message 1 and 2, while Observer2 handles message 2 and 3, and Observer3 handles message 1 and 3.
Then we have the Subject class which keeps an unordered map. The map keys are message IDs, and the values are lists of observers. The class has two methods subscribe() and publish(). The former takes an Observer and the message ID to be subscribed, and add the observer to the map with message ID as the key. publish() takes the message ID to be published, takes out the observers from the map who have subscribed to this message, and call their handle() method one by one.
Now in the main() function, we subscribes the observers to the messages they would like to handle. When the status of the subject changes, it notify the observers by publishing the corresponding messages.