Wednesday, 26 May 2021

Observer Design Pattern in C#

 Introduction

    In Observer design pattern an object 'subject' maintains the list of its dependent objects , observers, and notify them whenever there is a change in its state. It is a behavior design pattern.

It deals with below problems

- Define One to many dependency between objects without making them tightly coupled.

- Whenever there is a change in one object, other objects should get notified or updated.

UML diagram



Basic code example


public class Subject

    private IList<IObserver> _observers;
    private int state;

    // On change of this property, observers will be notified
    public int State{
        get{return state;}
        set{state = value; this.Notify();}
    }

    public Subject()
    {
        _observers = new List<IObserver>();
    }

    // Register Observer to get notification
    public void RegisterObserver(IObserver observer)
    {
        _observers.Add(observer);
    }

    //Remove Observer to stop getting notification
    public void RemoveObserver(IObserver observer)
    {
        _observers.Remove(observer);
    }

    //Send notification
    private void Notify()
{
var eventArg = new EventArg(){Value=4};
foreach(var observer in _observers)
observer.Execute(eventArg);
}
}

//Observer interface
public interface IObserver
{
    void Execute(EventArg eventarg);
}

public sealed class EventArg
{
public int Value{get;set;}
}

//Concrete ObserverA implementation of IObserver
public class ObserverA:IObserver
{
    public void Execute(EventArg eventArg)
{
Console.WriteLine($"ObserverA is execute & eventArg : {eventArg.Value}");
}
}

//Concrete ObserverB implementation of IObserver
public class ObserverB:IObserver
{
    public void Execute(EventArg eventArg)
{
Console.WriteLine($"ObserverB is execute & eventArg: {eventArg.Value}");
}
}

Program 
using System;
using System.Collections.Generic;

public class Program
{
public static void Main()
{
var subject = new Subject();
subject.RegisterObserver(new ObserverA());
subject.RegisterObserver(new ObserverB());
subject.State = 4;
}
}

//Since subject State property is changed when it is assigned with value 4, Observers get notification
//Output
    ObserverA is execute & eventArg : 4
   ObserverB is execute & eventArg: 4

In DotNet for this purpose there is Delegate & Event Type to achieve the same.

No comments:

Post a Comment