Observer

The observer pattern

The observer pattern is a behavioral pattern [GOF], which is a pattern classification concerned with the way classes or objects interact.
The pattern consists of a Subject and zero to many Observers it is the underlying pattern for the publish-subscribe pattern which is usually a little more complicated, involving a message queue and other 'moving parts'.
The pattern is very important and used ubiquitously, Microsoft even provide an interface for the pattern (rather confusingly) calling the subject, observable (IObservable<T>) and the observer, observer (IObserver<T>) and then in they're literature referring to them as the provider and the observer.
The observer pattern is concerned with the subject being able to notify it's observers when a change has occured. In that, when the subjects state changes, any observer interested in this state will be notified and can then update its own state accordingly.
It is claimed that this reduces coupling, as we'll see in code the subject keeps a collection of the observers (via some mechanism) and the observer has a method (or function etc) that is called by the subject. Both have to adhere to a specific contract.
Here's a simple example, with firstly the generic message:
// this is the information sent for the observer pattern from the Subject to it's observers
// we're just going to have a string property - Detail
// the class is immutable
class Message {
    public Message(string detail) {
        Detail = detail;
    }
    public string Detail { get; }
}
The next part is the implementation of IObservable<T>:
// not to reuse code (DRY) we'll use the Microsoft Interface IObservable<T>
// the interface requires the information (Message class) to be sent in the notification (T)
// and the implementation of the method Subscribe which also (just to make this easy!) needs another
// class which implements IDisposible (this is adding too much complexity)
class Subject : IObservable<Message> {

    List<IObserver<Message>> _observers;
    int _numberToTrack;

    public Subject() {
        _observers = new List<IObserver<Message>>();
        _numberToTrack = 0;
    }
    public IDisposable Subscribe(IObserver<Message> observer) {
        if (!_observers.Contains(observer)) {
            _observers.Add(observer);
        }
        // I'm not sure I agree with this, why not just have an unsubscribe method!
        return new Unsubscriber<Message>(_observers, observer);
    }
    // a simple change state method
    public void SetNumber(int newNumber) {
        _numberToTrack = newNumber;
        notifyObservers(new Message("The new number is " + _numberToTrack));
    }
    // a method that sends a message to the observers(subscribers)
    void notifyObservers(Message message) {
        foreach(var observer in _observers) {
            observer.OnNext(message);
        }
    }
    // this is the Unsubscriber this adds complexity but is what Microsoft require
    // which asks the question - why do all this just to remove an observer from the list?
    class Unsubscriber<Message> : IDisposable {
        List<IObserver<Message>> _observers;
        IObserver<Message> _observer;

        public Unsubscriber(List<IObserver<Message>> observers, IObserver<Message> observer) {
            _observers = observers;
            _observer = observer;
        }
        public void Dispose() {
            if (_observers.Contains(_observer)) {
                _observers.Remove(_observer);
            }
        }
    }
}
Here's the implementation of IObserver<T>:
// as this is using IObserver it has very low cohesion with unused methods!
class Observer : IObserver {
    private string _name;
    private IDisposable _unsubscriber;
    public Observer(string name) {
        _name = name;
    }
    public void Subscribe(IObservable subject) {
        Console.WriteLine("{0} subscribed",_name);
        _unsubscriber = subject.Subscribe(this);
    }
    public void Unsubscribe() {
        Console.WriteLine("{0} unsubscribed", _name);
        _unsubscriber.Dispose();
    }
    public void OnCompleted() {
        throw new NotImplementedException();
    }
    public void OnError(Exception error) {
        throw new NotImplementedException();
    }
    // each observer will replicate, in the real world this would be doing a real action
    public void OnNext(Message value) {
        Console.WriteLine("{0}: {1}", _name, value.Detail);
    }
}
The main program to test the implementation, which because of Microsoft's observable interfaces is a little odd:
class Program {
    static void Main(string[] args) {
        var subject = new Subject();
        var observerA = new Observer("observerA");
        var observerB = new Observer("observerB");
        var observerC = new Observer("observerC");

        var observerD = new Observer("observerD");

        observerA.Subscribe(subject);
        observerB.Subscribe(subject);

        // change the subjects number
        subject.SetNumber(10);

        observerC.Subscribe(subject);
        observerB.Unsubscribe();

        // weirdly I can subscribe observerD here but to unsubscribe I need to keep the unsubscribe object returned
        Console.WriteLine("Subscribing observerD from somewhere else!");
        var unsubcriberD = subject.Subscribe(observerD);

        subject.SetNumber(99);

        Console.WriteLine("Unsubscribing observerD from somewhere else!");
        unsubcriberD.Dispose();

        subject.SetNumber(321);

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
}
The output looks like this:
observerA subscribed
observerB subscribed
observerA: The new number is 10
observerB: The new number is 10
observerC subscribed
observerB unsubscribed
Subscribing observerD from somewhere else!
observerA: The new number is 99
observerC: The new number is 99
observerD: The new number is 99
Unsubscribing observerD from somewhere else!
observerA: The new number is 321
observerC: The new number is 321
Press any key to exit...

The Microsoft pattern is a little more complicated and does increase the coupling via the generic (in this case Message).

There is a simpler way to use the observer pattern when no message is sent and the observer just receives an update. The interfaces would be [GOF], :
interface ISubject {
    void Attach(IObserver observer);
    void Detach(IObserver observer);
    void Notify();
}

interface IObserver {
    void Update();
}
The observer has no knowledge of the subject but also doesn't know what state was changed but if it's obvious (ie unique event) then this pattern would be ok.
If extra information is required then Update could have arguments or a generic type.

An issue with the observer pattern is, if an observer is listening for many events in one or multiple subjects, in Microsofts documentation, they state to avoid this, but this doesn't seem possible in complex software.
This can be fixed by sending a unique id of the event (or something similar) in the notifying message but this makes the coupling a little more tighter, as the observer has unique knowledge of the subject, but this seems unavoidable.

Another issue is when the events stop, ie when a subject has finished sending messages (events) how does it tell the observer, 'I'm finished'. Microsoft solve this with the OnCompleted method which is used to instruct the observer that the subject is finished and to clean up any resources.

Summary

The observer pattern is a very well used pattern. It solves the issue of how does one object 'tell' another its state without heavily coupling the underlying classes.

References

wiki
Design Patterns [GOF]
dofactory observer pattern
microsoft observer pattern
codeproject observer pattern