Fri , Aug 04 2023
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
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();
}
}
I am an engineer with over 10 years of experience, passionate about using my knowledge and skills to make a difference in the world. By writing on LifeDB, I aim to share my thoughts, ideas, and insights to inspire positive change and contribute to society. I believe that even small ideas can create big impacts, and I am committed to giving back to the community in every way I can.
Leave a Reply