Introducing the Observer design pattern

Introducing the Observer design pattern

Read Time : 3 Minutes

Tuesday, 09 May 2023

Design patterns are proven solutions to software design problems. They help improve code quality, promote reusability, and increase maintainability. We use them to save time and produce quality, extensible and flexible code. In this article, we are going to introduce the Observer design pattern.

The Observer design pattern is a behavioral design pattern that connects an object to several dependent classes. This pattern provides the possibility that when the state of an object changes, its dependent objects are automatically notified and updated. The Observer pattern is useful when you need to maintain consistency between related objects without tightly coupling them.

 

The Observer pattern consists of various components:

  • Subject: It is an object whose status changes and this change is tracked by dependent objects. This object keeps a list of dependent objects and notifies them when the state changes.
  • Observer: The method that Subject calls during state change is defined in this interface.
  • Concrete Observer: This is the class that implements the Observer interface. This class should set what changes will happen in this class if the notify change is called through Subject.

Below is an example of how to implement the Observer pattern in C#:

interface IObserver
{
    void Update();
}
class Subject
{
    private List<IObserver> observers = new List<IObserver>();
    private int state;
    public int 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();
        }
    }
}
class ConcreteObserver : IObserver
{
    private string name;
    private Subject subject;
    public ConcreteObserver(string name, Subject subject)
    {
        this.name = name;
        this.subject = subject;
    }
    public void Update()
    {
       Console.WriteLine("{0} has received an update: {1}", name, subject.State);
    }
}
class Program
{
    static void Main(string[] args)
    {
        Subject subject = new Subject();
        ConcreteObserver observer1 = new ConcreteObserver("Observer 1", subject);
        ConcreteObserver observer2 = new ConcreteObserver("Observer 2", subject);
       subject.Attach(observer1);
        subject.Attach(observer2);
        subject.State = 5;
       subject.Detach(observer2);
        subject.State = 10;
        Console.ReadKey();
    }
}

In the example above, we have a Subject class that has mutable state. You also have a list of Observers that must be obeyed during the state change. When the state of the Subject changes, all connected Observers will receive these changes by calling the Update method. The connected Observer classes each have their own commands that they execute when they receive an update.

The Observer design pattern is useful when you need to maintain relationships between related objects without connecting them directly. When the state of an object changes, this change will be communicated to all connected objects and each of them will update themselves according to their own commands. By using the Observer pattern, you can create a more flexible and scalable design that separates the concerns of different components.

To read about other design patterns, you can use the list below. There is also a code repository on GitHub that includes all the design patterns.

design patterns

Creational:Factory Design Pattern
Builder Design Pattern
Singleton Design Pattern
Prototype Design Pattern
Abstract Factory Design Pattern
Structural:Adapter Design Pattern
Bridge Design Pattern
Composite Design Pattern
Decorator Design Pattern
Facade Design Pattern
Flyweight Design Pattern
Proxy Design Pattern
Behavioral:Chain of Responsibility Design Pattern
Command Design Pattern
Interpreter Design Pattern
Mediator Design Pattern
Memento Design Pattern
Observer Design Pattern
State Design Pattern
Strategy Design Pattern
Template Method Design Pattern
Visitor Design Pattern
Iterator Design Pattern
  • Share:
reza babakhani
Reza Babakhani

I am Reza Babakhani, a software developer. Here I write my experiences, opinions and suggestions about technology. I hope that what I write is useful for you.

Latest post

Service Mesh Simplifying Microservice Communication

In the ever-evolving landscape of software development, microservices architecture has gained considerable popularity due to its scalability, flexibility, and extensibility. However, as the number of microservices in an application increases, it becomes increasingly challenging to manage their communication and ensure that they are all properly visible. This is where Service Mesh comes into play.

The Importance of Edge Computing

Due to the speed of technological evolution, one of the concepts that has attracted a lot of attention and changes the way we interact with digital systems is edge computing.

What is event-driven architecture?

Event-driven architecture (EDA) is a software design pattern that has become increasingly popular in modern software development. In this architecture, the flow of data is determined by the occurrence of events. Unlike traditional centralized systems that are constantly checking for new status. Event-driven architecture is especially useful for systems that need to process large amounts of data in real-time.

leave a comment