Tutorials Design Patterns Mastery

Observer Pattern: Pub/Sub & Event-driven architecture

On this page

The Observer Pattern

The Observer Pattern defines a one-to-many dependency between objects. When one object (the Subject) changes state, all its dependents (the Observers) are notified and updated automatically. This is the heart of every modern UI framework and event-driven system.

1. Real-World .NET Example: events

In C#, we don't usually build Observe() and Notify() methods from scratch. We use the event keyword. This is the Observer pattern baked into the language.

public class StockTicker 
{
    // The SUBJECT
    public event Action<decimal> OnPriceChanged;

    public void UpdatePrice(decimal p) => OnPriceChanged?.Invoke(p);
}

// THE OBSERVERS
ticker.OnPriceChanged += (p) => Console.WriteLine($"UI updated: {p}");
ticker.OnPriceChanged += (p) => Logger.Log(p); 

2. Decoupling

The StockTicker has NO IDEA which classes are listening to it. You can add 50 new listeners (mobile app, email service, audit log) without changing a single line of logic in the ticker. This is the ultimate tool for handling "Secondary Effects."

4. Interview Mastery

Q: "What is the danger of the Observer pattern in C# if you forget to 'Unsubscribe'?"

Architect Answer: "Memory Leaks. When you write `ticker.OnPriceChanged += ObserverMethod;`, the Subject (ticker) now holds a strong reference to your observer class in its internal delegate list. As long as the ticker is alive, the Garbage Collector refuses to delete your observer, even if you are 'done' with it. This is a very common leak in WPF and long-running services. You MUST always use `-=` or implement `IDisposable` to clean up your subscriptions."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Design Patterns Mastery
Course syllabus
1. Introduction to Design Patterns
2. Creational Patterns
3. Structural Patterns
4. Behavioral Patterns
5. Modern Enterprise & Cloud Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details