Showing posts with label Design Pattern. Show all posts
Showing posts with label Design Pattern. Show all posts

Observer Design Pattern in C#.

In modern software applications, it’s common to have multiple components that need to react whenever something changes, like a weather display updating when the temperature changes, or different modules getting notified when an order is placed. Managing these updates manually quickly becomes messy and tightly coupled. This is where the Observer Design Pattern shines. It provides a clean, event-driven way for one object to notify many others automatically, making applications flexible, maintainable, and scalable.

What is the Observer Design Pattern?

The Observer Design Pattern is a behavioral design pattern used when you need one object (the Subject) to automatically notify other objects (Observers) of changes to its state.

This creates a one-to-many relationship between objects, where the Subject keeps a list of its Observers and notifies them whenever something changes.

Simple Words: Observer Pattern allows an object to publish events and multiple subscribers (observers) to react automatically.

When Do We Need the Observer Design Pattern?

Without the Observer Pattern:

  • You would manually call update functions for all dependent objects.
  • Code becomes tightly coupled.
  • Adding or removing listeners requires modifying the Subject class.
  • Any change breaks the Open/Closed Principle.

With Observer Pattern:

  • The subject doesn’t need to know who is observing.
  • Observers subscribe/unsubscribe on their own.
  • Adding new observers requires zero changes in the Subject.
  • It's event-driven and loosely coupled.
Real-Life Analogy: Think of it like a YouTube channel is a subject, and Subscribers are Observers. Whenever a channel uploads a new video, the YouTube channel notifies all your subscribers automatically. The channel doesn’t care how many people subscribed or who they are. Subscribers get updates based on their interests. 
This is exactly how the Observer Pattern works.

Observer Design Pattern

Observer Design Pattern Example.

Here is a C# example demonstrating the Observer pattern:
namespace PracticeCode.DesignPattern
{
    //Observer Interface
    public interface IObserver
    {
        void Update(float temperature);
    }
    //Subject Interface
    public interface ISubject
    {
        void RegisterObserver(IObserver observer);
        void RemoveObserver(IObserver observer);
        void NotifyObserver();
    }

    //Concrete Subject – Weather Station
    public class WeatherStation : ISubject
    {
        private List<IObserver> observers = new();
        private float temperature;

        public void RegisterObserver(IObserver observer)
        {
            observers.Add(observer);
        }
        public void RemoveObserver(IObserver observer)
        {
            observers.Remove(observer);
        }
        public void NotifyObserver()
        {
            foreach(var observer in observers)
            {
                observer.Update(temperature);
            }
        }

        //When temp change notify everyone
        public void SetTemperature(float newTemp)
        {
            Console.WriteLine($"\nWeatherStation: New Temperature = {newTemp}°C");
            temperature = newTemp;
            NotifyObserver();
        }
    }
    //Concrete Observers – Displays
    public class DigitalDisplay : IObserver
    {
        public void Update(float temperature)
        {
            Console.WriteLine($"Digital Display -> Updated Temperature: {temperature}°C");
        }
    }
    public class MobileDisplay : IObserver
    {
        public void Update(float temperature)
        {
            Console.WriteLine($"Mobile Display -> Updated Temperature: {temperature}");
        }
    }
}

Client Code in Program.cs, where the new observer is getting registered and getting notified whenever there is an update in temperature.
//Observers Subscribe
station.RegisterObserver(digital);
station.RegisterObserver(mobile);

//Observers Notify
station.SetTemperature(29.4f);
station.SetTemperature(30.2f);

//Observer Removed
station.RemoveObserver(digital);

//Observer Notify
station.SetTemperature(32.0f);
Output:
WeatherStation: New Temperature = 28.5°C
Digital DisplayUpdated Temperature: 28.5°C
Mobile AppTemperature Alert: 28.5°C

WeatherStation: New Temperature = 30.2°C
Digital DisplayUpdated Temperature: 30.2°C
Mobile AppTemperature Alert: 30.2°C

WeatherStation: New Temperature = 31.7°C
Digital DisplayUpdated Temperature: 31.7°C

This is one small example of how an Observer Design Pattern helps you write better and maintainable code, and in which all real-life conditions in which you can use this pattern.

These are some key points that you can keep in mind while writing an Observer Design Pattern Code:
  • Type: Behavioral
  • Purpose: Notify multiple objects automatically when one object changes.
  • Relationship: One-to-many
  • Helps With: Loose coupling, event-driven architecture
  • Key Methods: Register, Remove, Notify
  • Real Use Cases: Events, UI updates, stock market tickers, notifications
In Short, the Observer Pattern lets you build a system where one object publishes updates and many other objects automatically react to those updates.

DON'T MISS

AI
© all rights reserved
made with by WorkWithG