top of page
  • Writer's pictureCristian Duque

The Observer Pattern

Updated: Oct 30, 2023



It is one of the 23 design patterns described by the Gang of Four. This pattern establishes a one-to-many relationship between objects, where multiple dependent objects are automatically notified when the state of an object changes. The Observer pattern falls under the category of behavioural patterns.


The observer pattern comprises the following elements:

  • Subject (Observable): It contains a list of observers (consumers) that need to be notified when the subject state changes. It also provides methods to add or remove observers dynamically. The notifications may include context data that can be accessed by all observers.

  • Observer: It defines a standard interface that all concrete observers must implement to receive notifications about changes in the subject's state.

  • Concrete Observer: It is a concrete implementation of the observer interface that defines how it will react to subject updates.

  • Concrete Subject: It stores the state of concrete observers and sends notifications to them when its state has changed.


The Observable Pattern is also called the Publisher/Subscriber Pattern, but some differences exist. The former is commonly implemented synchronously, and the latter is called pub/sub messaging, which handles asynchronous message queue flows.


Thanks to a message broker, the publisher/subscriber pattern involves loose coupling between pubs/subs. On the other hand, the observable pattern has a subject (observable) that interacts with observers to avoid tight coupling between concrete observers and concrete subjects.



What are the benefits of the Observer Pattern:

  • Flexibility: Observers react independently to updates from the subject, and the subject and observer are loosely coupled.

  • Open/Closed Principle: Observers can be added or removed at anytime without affecting the pattern implementation.

  • Reusability: Observers can subscribe to multiple subjects if they adhere to the same update interface.

And the drawbacks:

  • Order updates: The order in which observers are updated is not always predictable. This can be difficult to handle in a system where order execution is critical.

  • Performance overhead: This pattern can introduce complexity, particularly when there are many observers to work with. It can be time-consuming to notify all subscribers.

  • Execution flow: When the pattern is not executed properly, it can lead to unexpected notifications throughout the system.


Check out my video:


2 views

Recent Posts

See All

Comments


bottom of page