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.

Factory Method Pattern in C#.

The Factory Design Pattern in C# is a creational design pattern that provides an interface for creating objects in a superclass while allowing subclasses to alter the types of objects that are created. This pattern encapsulates object creation logic, decoupling it from the client code that uses the objects.

It is beneficial for situations requiring flexibility, such as adding new product types without modifying existing client code.

When to use the Factory pattern?

  • Uncertainty about object type: When a class cannot predict the type of objects it needs to create, and this decision is better made at runtime.
  • Subclasses decide instantiation: When you want to delegate the responsibility of creating objects to subclasses, allowing them to alter the type of objects created.
  • Encapsulating creation logic: When the process of creating an object is complex, repetitive, or has many dependencies, the factory pattern can encapsulate this logic, making the code cleaner.
  • Extending with new products: When you want to easily add new product types in the future. Instead of modifying the client code, you can simply create a new subclass and implement its creation logic within the factory.
  • Decoupling client from concrete classes: To decouple the client code from the concrete classes it instantiates. The client only interacts with the factory and a common interface, not the specific implementations.
Let's understand a real-life problem and how we can fix that using the Factory Method.

Bad Example: Notification System.

Your application is using a Notification System to send notifications to users. Initially, you were sending only an Email Notification, so it was simple and easy. Later, you added SMS and a Push notification system. You have written if-else conditions to create different kinds of objects based on user requirements.

Example Code:
if (notification == "Email") new EmailNotification();
else if (notification == "SMS") new SMSNotification();
else if (notification == "PUSH") new PUSHNotification();

This is a bad approach to writing code because adding a new payment method means changing existing code, → violates the Open/Closed Principle. This code is also difficult to test and tightly coupled.

You might feel like you are writing too much code for a simple task, but in real-world, large and complex projects, the Factory Method Pattern helps you maintain, extend, and scale your application without modifying existing code.


Good Example: Notification System Using Factory Method.

fff
Step 1: Notification Interface/Abstract Class: Defines the common interface or abstract class for the objects that the factory will create. This ensures that all concrete products share a common contract.
public interface INotification
{
    void Send(string to, string message);
}

Step 2: Concrete Product Classes: Implement the INotification interface or inherit from the abstract product class, providing specific implementations.
public class EmailNotification : INotification
{
    public void Send(string to, string message)
    {
        Console.WriteLine($"Sending Email to {to} : {message}");
    }
}
public class SMSNotification : INotification
{
    public void Send(string to, string message)
    {
        Console.WriteLine($"Sending SMS to {to} : {message}");
    }
}
public class PUSHNotification : INotification
{
    public void Send(string to, string message)
    {
        Console.WriteLine($"Sending PUSH to {to} : {message}");
    }
}

Step 3: Creator/Factory Class (Abstract or Concrete): Declares the factory method, which returns an object of the INotification type. This method can be abstract, forcing subclasses to implement it, or it can provide a default implementation.
public abstract class NotificationFactory
{
    public abstract INotification CreateNotification();
}

Step 4: Concrete Creator/Factory Classes: Override the factory method to return instances of specific concrete product classes.
public class EmailFactory : NotificationFactory
{
    public override INotification CreateNotification()
    {
        return new EmailNotification();
    }
}
public class SMSFactory : NotificationFactory
{
    public override INotification CreateNotification()
    {
        return new SMSNotification();
    }
}
public class PUSHFactory : NotificationFactory
{
    public override INotification CreateNotification()
    {
        return new PUSHNotification();
    }
}
Client using the Factory:
NotificationFactory factory;
factory = new EmailFactory();
var email = factory.CreateNotification();
email.Send("user@example.com", "Welcome Email!");
I hope you now understand how and when to use the Factory Method Design Pattern.

The  Factory Method Pattern lets subclasses decide which object to create, helping you remove direct new calls, simplify object creation, and extend your application without modifying existing code.

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson