SOLID & Design Patterns Interview Question #35

What is the Observer Pattern?

Structural, Creational & Behavioral Patterns Junior Beginner

Quick Interview Answer

The Observer Pattern establishes a one-to-many relationship in which observers are notified when a subject changes or an event occurs. It reduces the need for the publisher to know concrete details about every consumer.

Detailed Explanation

The Observer Pattern establishes a one-to-many relationship in which observers are notified when a subject changes or an event occurs. It reduces the need for the publisher to know concrete details about every consumer.

In .NET, events and delegates are common mechanisms for implementing observer-style communication. Care is needed with subscriptions because long-lived publishers can retain subscribers and contribute to memory leaks.

Code Example

public class OrderService
{
    public event EventHandler<Order>? OrderCreated;

    protected virtual void OnOrderCreated(Order order)
        => OrderCreated?.Invoke(this, order);
}