Observer pattern example in C#

This article has a simple sample of using Observer pattern. The description of this pattern you can read in other resources or you can understand the basis of the pattern exploring this example. Also, you can download an example in C#. This pattern is also known as Dependents pattern or Publish-Subscribe pattern

class Subject
{
    private List<Observer> observers = new List<Observer>();
 
    public void Attach(Observer observer)
    {
        observers.Add(observer);
    }
 
    public void Detach(Observer observer)
    {
        observers.Remove(observer);
    }
 
    public void Notify()
    {
        foreach (var observer in observers)
        {
            observer.Update();
        }
    }
}
abstract class Observer
{
    abstract public void Update();
}
class ConcreteSubject : Subject
{
    private int value;
 
    public int Value
    {
        get
        {
            return value;
        }
        set
        {
            this.value = value;
            Notify();
        }
    }
}
class ConcreteObserver : Observer
{
    private ConcreteSubject subject;
 
    public override void Update()
    {
        Console.WriteLine("Subject value is {0}.", subject.Value);
    }
 
    public ConcreteObserver(ConcreteSubject subject)
    {
        subject.Attach(this);
        this.subject = subject;
    }
 
    ~ConcreteObserver()
    {
        subject.Detach(this);
    }
}
class Program
{
    static void Main(string[] args)
    {
        var concreteSubject = new ConcreteSubject();
        var concreteObserver = new ConcreteObserver(concreteSubject);
 
        concreteSubject.Value = 10;
    }
}

As an output you will have: Subject value is 10.

Links

Observer pattern description in Wikipedia