Observer Design Pattern

Learn via video courses
Topics Covered

Overview

Observer design pattern falls under the category of behavioral design patterns. The Observer Pattern maintains a one-to-many relationship among objects, ensuring that when the state of one object is changed, all of its dependent objects are simultaneously informed and updated. This design pattern is also referred to as Dependents.

A subject and observer(many) exist in a one-to-many relationship. Here the observers do not have any access to data, so they are dependent on the subject to feed them with information.

When Will We Need Observer Design Pattern?

One could implement the observer design patterns when designing a system where several objects are interested in any possible modification to a specific object. In other words, the observer design pattern is employed when there is a one-to-many relationship between objects, such as when one object is updated, its dependent objects must be automatically notified.

One to Many Relation between subject and object

Real-World Example: If a bus gets delayed, then all the passengers who were supposed to travel in it get notified about the delay, to minimize inconvenience. Here, the bus agency is the subject and all the passengers are the observers. All the passengers are dependent on the agency to provide them with information about any changes regarding their travel journey. Hence, there is a one-to-many relationship between the travel agency and the passengers.

Other Examples of observer design patterns:

  • Social Media Platforms for example, many users can follow a particular person(subject) on a social media platform. All the followers will be updated if the subject updates his/her profile. The users can follow and unfollow the subject anytime they want.
  • Newsletters or magazine subscription
  • Journalists providing news to the media
  • E-commerce websites notify customers of the availability of specific products

Consider the following scenario: There is a new laughter club in town, with a grand opening, it caught the attention of a lot of people interested in being a member of the club. Thrilled with the overwhelming response, the club owner was a bit worried about the smooth management and involvement of all the members.

The observer design pattern is the best solution to the owner’s problem. The owner here is the subject and all the members of the club are observers. The observers have no access to the club’s information and the upcoming events unless the owner notifies them of it. Also, the members have the option to opt out of the club whenever they want to. This allows the owner to easily manage and engage all of the members.

How does Observer Design Patterns work?

Structure

Pattern in Obeserver Design

  • The subject delivers events that are intriguing to the observers. These events occur due to changes in the state of the subject or the execution of certain behaviors. Subjects have a registration architecture that enables new observers to join and existing observers to withdraw from the list.
  • Whenever a new event occurs, the subject iterates through the list of observers, calling the notify method provided in the 'observer' interface.
  • The notification interface is declared by the Observer interface. It usually includes an updating method. The method may include numerous options that allow the subject to provide event information together with the update.
  • Concrete Observers do certain activities in response to alerts sent by the Subject. All the concrete observer classes should implement the base observer interface, and the subject interface is coupled only with the base observer interface.
  • Sometimes, observers want some additional context in order to properly process any update notified by the Subject. As a result, the Subject frequently supplies some contextual information as parameters to the notification function. The subject can pass itself as an argument, allowing the subject to immediately retrieve any needed data.

Implementation

  1. Declare an Observer interface with an update method at the least.
  2. Declare the subject interface and a couple of methods for attaching and detaching observer objects from the list of observers. (Remember that publishers must only interact with subscribers through the subscriber interface.)
  3. Create a concrete subject class if needed and add the subscribers’ list to this class. Since this concrete class extends the Subject interface, it inherits all its properties including adding and removing observers. Every time something significant happens inside the subject class, it must inform to all the observers about it.
  4. In concrete observer classes, add the update notification methods. Some observers might want basic background information about the occurrence. The notification method accepts it as an input.

Pseudo-Code

Code Example

Java

Output:

Python

Output:

C++

Output:

Pros

  1. This design pattern allows information or data transfer to multiple objects without any change in the observer or subject classes.
  2. It adheres to the loose coupling concept among objects that communicate with each other.
  3. This design pattern follows the Open/Closed Principle, which says that entities should be open for extension but closed for modification. Here the observers can easily be added or removed anytime without any change in the code.

Cons

  1. The Observer pattern can increase complexity and potentially cause efficiency issues if it's not executed properly.
  2. The fundamental shortcoming of this design pattern is that the subscribers/observers are updated in a random sequence.

Comparison With Other Similar Design Patterns

  • Chain of Responsibility, Command, Mediator, and Observer are all methods for decoupling senders and receivers, but each has its own set of trade-offs. A sender request is passed through a chain of possible receivers using the Chain of Responsibility . A sender-receiver relationship with a subclass is generally specified by the command pattern. In Mediator, senders and receivers make implicit references to one another. Observer pattern offers a decoupled interface that enables the configuration of numerous receivers at the time of execution.
  • The observer pattern and the mediator pattern are very similar. The distinction is because an Observer object spreads communication among objects by incorporating observer and subject objects, but a Mediator object encapsulates interaction among different objects.
  • A publisher object uses the observer pattern to send information to subscriber objects. The proxy pattern, on the other hand, is used to wrap a type of special object with one or several different objects.

Transform your passion for design into tangible skills with our Instagram System Design course, your gateway to design excellence.

FAQs

Q: What is Loose Coupling?

A: A loosely coupled system is one where components are poorly linked with each other so that modifications in one component have the slightest effect on the existence or operation of that other component. The amount of insider understanding that one component has of the other is referred to as coupling.

Q: What is the difference between Publish-Subscribe and Observer Pattern?

A: Observer is an object-action oriented pattern, while Publish-Subscribe is a network-oriented architectural pattern. They're both utilized at diverse levels of software. Secondly, because the observer and the subject are coupled, the observer pattern must be implemented in the same space, but because publish-subscribe is a cross-application communication pattern, there is no such limitation.