Discovering the Observer Pattern

Discovering to the Observer Pattern

Welcome back! We're continuing our exploration of Behavioral Patterns. In this lesson, we will delve into the Observer Pattern, another fundamental pattern that emphasizes object communication and responsibility distribution. This pattern allows an object, known as the subject, to maintain a list of its dependents, called observers, and notify them automatically of any state changes, usually by calling one of their methods.

Previously, we looked at the Command Pattern, which encapsulates a request as an object. Now, let's build on that knowledge and explore how the Observer Pattern facilitates communication between objects in a seamless and efficient manner.

Understanding the Observer Pattern

Imagine you subscribe to a daily news service. Instead of checking the news website constantly, you get notifications whenever there's an update. Here, the news service is the subject, and you are an observer who gets notified about the news updates.

Main Components:

  1. Subject: Keeps track of observers and sends updates.
  2. Observer: Gets notified with updates from the subject.

With this basic understanding, let's move on to defining an interface, which will act as our observer in the Observer Pattern.

Defining the ISubscriber Interface

We'll start by defining the ISubscriber interface that lays out the method for receiving updates. This interface represents an Observer:

public interface ISubscriber
{
    void Update(string news);
}

This ISubscriber interface defines the Update method. This method will be called by the subject to notify subscribers of any updates.

Creating the NewsPublisher Class

Next, we need to create the NewsPublisher class, which acts as the Subject. This class maintains a list of subscribers and provides methods to add, remove, and notify them:

public class NewsPublisher
{
    private List<ISubscriber> subscribers = new List<ISubscriber>();

    public void AddSubscriber(ISubscriber subscriber)
    {
        subscribers.Add(subscriber);
    }

    public void RemoveSubscriber(ISubscriber subscriber)
    {
        subscribers.Remove(subscriber);
    }

    public void Publish(string news)
    {
        foreach (ISubscriber subscriber in subscribers)
        {
            subscriber.Update(news);
        }
    }
}

The NewsPublisher class includes methods to manage subscribers and to notify them with updates, ensuring efficient communication between the subject and its observers.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal