Design Patterns | Observer Pattern Explained Using C#

An object-oriented programming design pattern is the observer pattern. It is a behavioural pattern that identifies an object relationship of one to many. When an object in this pattern changes state, all of its dependents are alerted and changed automatically. We'll talk about the observer pattern's C# implementation in this blog article.

The Observer Pattern in C#

The subject and the observer are the two different kinds of objects in the observer pattern. The object being observed is the subject, and the object viewing the subject is the observer. As the state of the subject changes, the observer can be automatically notified using the observer pattern.

To implement the observer pattern in C#, we will create an interface called ISubject. This interface will define the methods that the subject class will implement.

1
2
3
4
public interface ISubject 
{
void Attach(IObserver observer); void Detach(IObserver observer); void Notify(); 
}

To attach an observer to the topic, use the Attach() method. Detaching an observer from the subject is accomplished using the Detach() method. To alert all observers that the subject has changed, use the Notify() method.

Also, we'll design an interface named IObserver. The methods that the observer class will implement are specified by this interface.


1
2
3
4
public interface IObserver
{
    void Update(ISubject subject);
}


The Update() method is used to update the observer when the subject changes.

Next, we will create a concrete implementation of the ISubject interface called Subject. This class will hold the state of the subject and maintain a list of all the observers.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Subject : ISubject
{
    private List<IObserver> _observers = new List<IObserver>();
    private int _state;

    public int State
    {
        get { return _state; }
        set
        {
            _state = value;
            Notify();
        }
    }

    public void Attach(IObserver observer)
    {
        _observers.Add(observer);
    }

    public void Detach(IObserver observer)
    {
        _observers.Remove(observer);
    }

    public void Notify()
    {
        foreach (IObserver observer in _observers)
        {
            observer.Update(this);
        }
    }
}

The subject's state is kept on State property. The Notify() method is used to alert all observers when the state changes.


Also, we'll develop Observer, an actual implementation of the IObserver interface. When the subject changes, this class will implement the Update() function and update its state.

Suggested Read : Visitor Design Pattern


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class Observer : IObserver
{
    private string _name;
    private int _observerState;

    public Observer(string name)
    {
        _name = name;
    }

    public void Update(ISubject subject)
    {
        _observerState = subject.State;
        Console.WriteLine("Observer {0}'s new state is {1}", _name, _observerState);
    }
}

The Update() method updates the observer's state when the subject changes.

Finally, we'll create a program that illustrates the observer pattern. In this program, we will build a subject and pair it with two observers. We will then change the subject's state and see how the observers are notified.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
static void Main(string[] args)
{
    Subject subject = new Subject();

    Observer observer1 = new Observer("Observer 1");
    Observer observer2 = new Observer("Observer 2");

    subject.Attach(observer1);
    subject.Attach(observer2);

    subject.State = 5;
    subject.Detach(observer2);
    subject.State = 10;

    Console.ReadKey();
}




(); }

Comments

Popular posts from this blog

Creating RESTful Minimal WebAPI in .Net 6 in an Easy Manner! | FastEndpoints

Mastering Concurrency with Latches and Barriers in C++20: A Practical Guide for Students

Graph Visualization using MSAGL with Examples