Learn the Observer Design Pattern: Clear and Easy Approaches

Unlocking the Power of Observer Pattern: Enhance Your Software Development Skills with Flexible and Maintainable Code

Learn the Observer Design Pattern: Clear and Easy Approaches

Introduction

In this article, we will learn and understand the Observer pattern. Design patterns are a crucial concept if you want to distinguish yourself as a software developer from an average one.

The Observer pattern is a significant design pattern among others. Design patterns assist developers in creating software that is more flexible, extensible, and maintainable by offering time-tested solutions to common issues.

Prerequisites

  • Any programming language.

  • Basic programming concepts.

  • Object-oriented concepts.

  • Design pattern basics. (Good to know but, Not required)

What is the Observer Pattern?

The Observer Pattern is a design pattern that allows you to establish a subscription-based method for notifying multiple observers about any state changes occurring in the object they are monitoring.

Why should I use the Observer Pattern?

The Observer Pattern is a renowned design pattern that falls under the behavioural pattern category. It promotes code reusability, ease of maintenance and readability, flexibility in managing relationships between objects, and event-driven architecture, and is widely utilized in numerous software companies.

What kind of problem does the Observer Pattern solve?

The main use of the observer pattern is to handle event-driven scenarios. The observer pattern is used when there is a one-to-many relationship between objects, such as when one object is modified, its dependent objects are to be notified automatically. The Observer Pattern also supports dynamic updates and changes, and enhances code reusability, making applications more modular, maintainable, and scalable.

Real-world use of the observer pattern can be seen in most social media platforms. Users can post updates and follow other users to receive updates in their news feed. The Observer design pattern can be used to implement user accounts as subjects and news feed components as observers.

When a user posts an update, the subjects notify the observing news feed components, which can then update the display of the news feed for the relevant followers. This allows users to see the latest updates from the users they follow in their news feed without directly depending on the user accounts or tightly coupling with other components of the social media platform.

Now, let's look into the code side of how the observer pattern works.

Code Example Using React.js

Let's write observable code using an ES6 class, which is an easy way to create it.

class Observable {
  constructor() {
    this.observers = [];
  }

  subscribe(f) {
    this.observers.push(f);
  }

  unsubscribe(f) {
    this.observers = this.observers.filter(subscriber => subscriber !== f);
  }

  notify(data) {
    this.observers.forEach(observer => observer(data));
  }
}

export default new Observable();

An observable object usually contains 3 important parts:

  • observers: An array of observers that will get notified whenever a specific event occurs

  • Using subscribe method: A method to add observers to the observers list

  • Using unsubscribe method: A method to remove observers from the observers list

  • Using notify method: A method to notify all observers whenever a specific event occurs

Let's build a simple and basic app using ReactJS to demonstrate the Observer design pattern.

In this example, we aim to monitor user interactions within the application. Whenever a user clicks a button or toggles a switch, we want to record this event along with its timestamp. In addition to logging the event, we also want to generate a toast notification that appears each time an event takes place.

While the observer pattern can be employed in various scenarios, it proves particularly beneficial when dealing with asynchronous, event-based data. For instance, you might want specific components to be notified once certain data has finished downloading, or when users submit new messages to a message board, ensuring that all other members receive notifications. Now, you can create something impressive by incorporating the observer pattern into your upcoming project.

Here are some examples of React-related frameworks or libraries that incorporate the Observer pattern:

  • RxJS

  • Redux

  • MobX

Pros and Cons

Let's discuss the pros and cons of the Observer Pattern.

Pros

  • Uses the single-responsibility Principle.

  • Observable objects are not tightly coupled and can be decoupled easily.

  • Establish relations between objects at runtime.

Cons

  • Too Complex.

  • Subscribers are notified in random order.

  • Cause Performance issues when notifying all subscribers.

Conclusion

In conclusion, the Observer pattern is a powerful and widely used design pattern that provides a subscription-based methodology for notifying multiple observers about any state changes that will happen to the object they are observing.

It helps with code reusability, easy maintenance and readability, and flexibility to manage relationships between objects.

While it can be complex and may cause performance issues when notifying all subscribers, it ultimately enhances code modularity, maintainability, and scalability. By incorporating the Observer pattern into your projects, you can create more flexible and extensible software solutions.

Thank you for reading my article. Iโ€™m going to share more tech content soon. So, Please Follow Me, Feel free to comment and share your suggestions/thoughts.

Also, Follow me on Twitter @asenseofpradhyu. I share daily Cloud, System Design, Code, and many more tech stuff ๐Ÿ˜Š

Resources

Did you find this article valuable?

Support Pradhumansinh Padhiyar by becoming a sponsor. Any amount is appreciated!

ย