Design Pattern – Observer

C# CONCEPTS

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.

Photo by Christina Morillo from Pexels

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

  • Basic knowledge of OOPS concepts.
  • Any programming language knowledge.

The article demonstrates the usage of observer design patterns using the C# programming language. So, to begin with, C#

View at Medium.com

Learning Objectives

  • 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.

  • Notify: To notify all the followers.
  • AddFollower: Add a new follower to the celebrity list.
  • 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.

https://gist.github.com/ssukhpinder/c98ce6c8c56113f6335a34f9782a3f49

ConcreteSubject named “Sukhpinder.cs”

https://gist.github.com/ssukhpinder/da667168bdc1f77333a201c87abd6b78

How to use observer pattern?

The following use case shows that whenever the below statement is executedsukhpinder.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.”

https://gist.github.com/ssukhpinder/78c9f9c7986b4b006a0d5eb48afcb1de

Output


Github Repo

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

View at Medium.com

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.

More design patterns

View at Medium.comView at Medium.comView at Medium.comView at Medium.comView at Medium.com

Leave a comment