Observer Design Pattern With C# Example

Observer Design Pattern With C# Example

This article is to describe the Observer Design Pattern. Also we'll learn how to implement this in C#. In this article, following points shall be covered:

1. What is Observer Pattern?

2. What type of problem it solves with a real world example?

4. Implementation in C# language.


What is Observer Pattern?

Observer Pattern is a behavioral design pattern which provides a mechanism to notify multiple objects if there is a change in state of some other type of object. In this pattern, an object which has some interesting state is watched by multiple objects known as Observers and the object which is being watch is known as Subject.

What type of problem it solves with a real world example?

To understand the problem, lets take a real world example. A user wants to buy a mobile from an online ecommerce portal. When he checked the portal, that product was not available. Now, he needs to check the portal multiple times till the product is not available. This is not good as per user's perspective.

Now, Portal has a number of registered users. When the product is available, the portal has to sends the notification to all the registered user's. Let's portal sends an email to notify the users. Let's only some of the users are interested in that product. So, for all other user's these emails are like spam.

What if there is some mechanism  by which the user that is interested in that product, gets subscribed so that whenever the product is available only those users get the notification mail. Here, the Observer Pattern solves the problem.

Implementation in C# language

Following is the C# code to implement the observer design pattern:

Add ObserverPattern.cs and use the code.

=======================

public interface IProduct
    { 
        string Name { get; set; }

        float Price { get; set; }

        bool IsAvailable { get; set; }

        void Subscribe(IUser user);

        void Unsubscribe(IUser user);

        void Notify();
    }

    public interface IUser
    { 
        string UserName { get; set; }

        void Update(IProduct product);
    }

    public class Mobile : IProduct
    {
        List users = new List();

        public Mobile(string name, float price)
        {
            Name = name;
            Price = price;
        }

        public string Name { get; set; }
        public float Price { get; set; }

        private bool _IsAvailable;
        public bool IsAvailable { get {
                return _IsAvailable;
            }
            set {
                
                _IsAvailable = value;
                if (value == true)
                {
                    Notify();
                }
            }
        }

        public void Notify()
        {
            users.ForEach(user => user.Update(this));
        }

        public void Subscribe(IUser user)
        {
            users.Add(user);
        }

        public void Unsubscribe(IUser user)
        {
            users.Remove(user);
        }
    }

    public class User : IUser
    {
        public string UserName { get; set; }

        public User(string name)
        {
            UserName = name;
        }


        public void Update(IProduct product)
        {
            Console.WriteLine($"Hi {UserName}, Product {product.Name} is now available on portal of Rs.{product.Price}");
        }
    }
        

In Program.cs, use the code

===================

using ObserverPattern;

Mobile samsungMobile = new Mobile("Samsung M30", 150000);

User user1 = new User("Pramod");
User user2 = new User("Pankaj");
User user3 = new User("Jyoti");

samsungMobile.Subscribe(user1);
samsungMobile.Subscribe(user3);

Console.WriteLine("Press 'T' or 'F' to change the product availability state to True or false.");

var key = Console.ReadKey().Key;
Console.WriteLine();
if (key == ConsoleKey.T)
{
    samsungMobile.IsAvailable = true;
}
else if (key == ConsoleKey.F)
{
    samsungMobile.IsAvailable = false;
}

Console.WriteLine("=====================");
//Please check the output, user1 and user3 should get notified

samsungMobile.IsAvailable = false;
//Now let's unsubscribe user3
samsungMobile.Unsubscribe(user3);

key = Console.ReadKey().Key;
Console.WriteLine();
if (key == ConsoleKey.T)
{
    samsungMobile.IsAvailable = true;
}
else if (key == ConsoleKey.F)
{
    samsungMobile.IsAvailable = false;
}
//Please check the output, only user1 should get notified as user3 got unsubsribed

Console.ReadLine();
        

Let's understand the code

In above code, we have created to interfaces, IProduct and IUser.

The subject will implement IProduct and all observers shall implement IUser.

The product has 3 properties, Name, Price and IsAvailable. IsAvailabe is the state in which all the users are interested.

Whenever, IsAvailable state value is true, all the users shall get notified.

Subject has three methods, Subscribe() to subscribe for the notification, Unsubscribe to unsubscribe for any further notification and Notify() to notify all observers using observer's Update() method.

The observer has Update() method which prints the message in the console when the product's IsAvailable state is set to true. It may be a mail/sms as per business need.

In Program.cs, we create 1 Mobile object and 3 Users object. Only User1 and User3 user subscribe themselves to get the notification. Now, when the product is available only User1 and User3 get the notification.

We set the IsAvailable state to false, No notification will be sent. Then User3 unsubscribe himself. Now, when the state is again set to true only User1 will get the notification.

Hope, you understand this pattern with this real world example.

If you like the post, please like, comment and share. Thanks in advance. 😊

Microsoft implemented it very practically in new microsoft community toolkit in IMessenger integration where viewmodels can interact as receiver and obsrver and viewmodels do not need to have a instance dependencies of other view models in order to share common data

Like
Reply

The Publisher-Subscriber (Pub-Sub) pattern and the Observer design pattern are similar and share a fundamental concept of enabling communication between components. In both patterns, a subject (publisher) notifies a list of observers (subscribers) about changes. The key difference lies in the implementation details and terminology. In the Observer pattern, the subject maintains a direct list of observers, whereas in Pub-Sub, a publisher distributes messages to subscribers without their explicit knowledge of each other. Pub-Sub often involves a more decentralized, message-centric approach, while the Observer pattern focuses on the relationship between a subject and its observers. Despite distinctions, both patterns offer decoupling, flexibility, and efficient communication in software design.

To view or add a comment, sign in

Others also viewed

Explore content categories