Design Pattern – Observer

According to Gang of Four, observer pattern defines dependency b/w two or more objects. So when one object state changes, then all its dependents are notified.

In other words, a change in one object initiates the notification in another object.


Use Case

Let’s take an example of an Instagram celebrity influence who has “x” number of followers. So the moment the celebrity adds a post, then all the followers are notified.

Let us implement the aforementioned use case using Observer Design Pattern.


Prerequisites

  1. Basic knowledge of OOPS concepts.

  2. Any programming language knowledge.

The article demonstrates the usage of observer design patterns using the C# programming language.


Learning Objectives

  1. How to code using an observer design pattern?

Getting Started

According to the use case, the first implement an interface that contains what actions a celebrity can perform. It is known as “Subject.”

public interface ICelebrityInstagram{
 string FullName { get; }
 string Post { get; set; }
 void Notify(string post);
 void AddFollower(IFollower fan);
 void RemoveFollower(IFollower fan);
}

The Subject contains the following member functions.

  1. Notify: To notify all the followers.

  2. AddFollower: Add a new follower to the celebrity list.

  3. RemoveFollower: Remove a follower from the celebrity list.

Now implement the observer “IFollower” interface, which contains the “Update” member function for notification.

public interface IFollower{
 void Update(ICelebrityInstagram celebrityInstagram);
}

Finally, it’s time to implement “Concrete Implementation” for both “Subject” and “Observer.”


ConcreteObserver named “Follower.cs”

It provides an implementation of the Update member function, which outputs the celebrity name & post to the console.

ConcreteSubject named “Sukhpinder.cs”


How to use observer pattern?

The following use case shows that whenever the below statement is executed sukhpinder.Post = “I love design patterns.”; the Update method is triggered for each follower, i.e., each follower object is notified of a new post from “Sukhpinder.”


Output

Github Repo

The following repository shows the above use case implementation using an Observer Design Pattern in the console-based application.

Link: https://github.com/ssukhpinder/ObserverPattern


Thank you for reading, and I hope you liked the article. Please provide your feedback in the comment section.


Follow me on

C# Publication, LinkedIn, Instagram, Twitter, Dev.to, Pinterest, Substack, Wix.


Tags: #ObserverDesignPattern #DotnetCore #DesignPatterns #Dotnet #Programming

Recent Posts

See All

Design Pattern – Adapter

#Aspnetcore #AdapterDesignPattern #Csharp #DesignPatterns #Dotnet According to Gang of Four, the Adapter Pattern converts the interfaces of a class into interfaces that the client requires. In other w