Post Details

What is the Observer Design Pattern in C Sharp .Net ?

np

Fri , Aug 04 2023

np

Article 3 on design pattern-

What is the Observer Design Pattern in C#?

The Observer Design Pattern is a behavioral design pattern that defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. It is used when you want to notify other objects about changes without coupling them to the object that changes. Here is an example of the Observer Design Pattern in C#:

using System;

using System.Collections.Generic;


public interface IObserver

{

    void Update(ISubject subject);

}


public interface ISubject

{

    void Attach(IObserver observer);

    void Detach(IObserver observer);

    void Notify();

}


public class ConcreteSubject : ISubject

{

    private readonly List _observers = new List();

    private string _state;


    public string 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);

        }

    }

}


public class ConcreteObserver : IObserver

{

    private readonly string _name;


    public ConcreteObserver(string name)

    {

        _name = name;

    }


    public void Update(ISubject subject)

    {

        Console.WriteLine("{0} received notification: {1}", _name, ((ConcreteSubject)subject).State);

    }

}


class Program

{

    static void Main()

    {

        ConcreteSubject subject = new ConcreteSubject();


        subject.Attach(new ConcreteObserver("Observer 1"));

        subject.Attach(new ConcreteObserver("Observer 2"));


        subject.State = "New state";


        Console.ReadKey();

    }

}




Leave a Reply

Please log in to Comment On this post.