Observer Pattern

Introduction and Implementation of Observer Design Pattern


Category: Design Patterns Tags: C#

Observer Pattern - Code Files

Introduction

    Observer pattern is Behavioral Design Pattern. Observer pattern is used to let you build publish subscription mechanism to notify multiple subscribers.

Suppose an ecommerce website has multiple microservices to process events like one microservice processes events when order is placed and other does processes order cancellation events. In this case we can make use of observer pattern, microservices can subscribe to required events.

Implementation

    Let's define events first.

public class BaseEvent
{ }

public class OrderPlacedEvent : BaseEvent
{ }

public class OrderCancelledEvent : BaseEvent
{ }

Now we have to create an event manager which lets subscribers to subscribe for an event and also lets publisher to publish events.

public class EventManager<T>
{
    private static Dictionary<string, List<Action<T>>> _events;

    static EventManager()
    {
        _events = new Dictionary<string, List<Action<T>>>();
    }

    public void Subscribe(BaseEvent eventType, Action<T> action)
    {
        var eventTypeName = eventType.GetType().Name;
        if (_events.ContainsKey(eventTypeName))
        {
            _events[eventTypeName].Add(action);
        }
        else
        {
            _events.Add(eventTypeName, new List<Action<T>>() { action });
        }
    }

    public void Publish(BaseEvent eventType, T data)
    {
        var eventTypeName = eventType.GetType().Name;
        if (_events.ContainsKey(eventTypeName))
        {
            var subscribers = _events[eventTypeName];
            foreach (var subscriber in subscribers)
            {
                subscriber(data);
            }
        }
    }
}

I have created a dictionary which can hold list of subscribers for each event whenever an event occurs EventManager publishes event to all the subscribers of same event. Now let's run the code.

var eventManager = new EventManager<string>();
var subscriber1 = (string data) => { Console.WriteLine("Sub1: " + data); };
var subscriber2 = (string data) => { Console.WriteLine("Sub2: " + data); };
var subscriber3 = (string data) => { Console.WriteLine("Sub3: " + data); };

eventManager.Subscribe(new OrderPlacedEvent(), subscriber1);
eventManager.Subscribe(new OrderPlacedEvent(), subscriber2);
eventManager.Subscribe(new OrderCancelledEvent(), subscriber3);

eventManager.Publish(new OrderPlacedEvent(), "Order Placed");
Console.WriteLine();
eventManager.Publish(new OrderPlacedEvent(), "Order Placed");
Console.WriteLine();
eventManager.Publish(new OrderCancelledEvent(), "Order Cancelled");

Output

Sub1: Order Placed

Sub2: Order Placed

 

Sub1: Order Placed

Sub2: Order Placed

 

Sub3: Order Cancelled

 


Like 0 People
Last modified on 25 October 2022
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 164
Questions: 16
Given Best Solutions: 16 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x