Software

Observer Pattern

Visualization example: let’s say you want to know about the new articles of this blog. You can make software which will check the updates every 1 minute or every 1 hour or even a day. But maybe you need to know immediately, then the observer pattern can help, where the blog will notify you every time a new post is added. You would subscribe to the blog. Every time when new post is published, the blog will notify each subscriber, including you. Hence you don’t need to pull for this information at some interval.

Subject – blog, will keep the list of Observers (subscribers to the blog).

We’ll have a Subject superclass, that defines three methods:

  • Allow a new observer to subscribe.
  • Allow a current observer to unsubscribe.
  • Notify all observers about a new blog post.

Also have to create an Observer interface with methods that an observer can be notified to update itself.

The Blog class will be a subclass of the Subject base class.

Subscriber class will implement the Observer interface.

Observer Pattern Sequence Diagram.png
Observer pattern sequence diagram
Observer Pattern Class Diagram.png
Observer pattern class diagram

Step 1. Add the Subject base class:

public class Subject {
    private List<Observer> observers = new List<Observer>();

    public void RegisterObserver(Observer observer) {
        observers.Add(observer);
    }

    public void UnregisterObserver(Observer observer) {
        observers.Remove(observer);
    }

    public void Notify() {
        foreach(Observer observer in observers){
            observer.Update();
        }
    }
}

Step 2. The Blog class which implements the Subject:

//The Blog will inherit the RegisterObserver, UnregisterObserver,
//and Notify methods, and have the other responsibilities of managing the blog.
public class Blog: Subject {
    private string state;

    public string GetState(){
        return state;
    }

    // blog responsibilities
    ...
}

Step 3. The Observer interface and imlementation, which make sure all observer objects behave the same way:

public interface Observer(){
    public void Update();
}

public class Subscriber: Observer {
    //get the blog change
    ...
}

One thought on “Observer Pattern

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.