Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

ReadMe.md

Observer Design Pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically

Overview

The Observer pattern is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they're observing. It's also known as the Publish-Subscribe pattern.

Implementation Details

This implementation demonstrates a product availability notification system where users can subscribe to get notified when a product becomes available:

Key Components:

  • ISubject Interface: Defines methods for managing observers (RegisterObserver, RemoveObserver, NotifyObservers)
  • IObserver Interface: Defines the Update method that observers must implement
  • Subject (Concrete Subject): Maintains product information and notifies observers of state changes
  • Observer (Concrete Observer): Represents users who want to be notified about product availability

Classes:

  • ISubject - Subject interface with observer management methods
  • IObserver - Observer interface with Update(string availability) method
  • Subject - Concrete subject that maintains product state (ProductName, ProductPrice, Availability)
  • Observer - Concrete observer representing users with UserName property

Usage Example:

// Create a product subject
Subject RedMI = new("Red MI Mobile", 1000, "Out Of Stock");

// Create observers (users)
Observer user1 = new("Tushar");
Observer user2 = new("Karan");
Observer user3 = new("Kuldeep");

// Subscribe users to product notifications
user1.AddSubscriber(RedMI);
user2.AddSubscriber(RedMI);
user3.AddSubscriber(RedMI);

// Check current availability
Console.WriteLine("Red Mi Mobile current state: " + RedMI.GetAvailability());

// Unsubscribe a user
user3.RemoveSubscriber(RedMI);

// Change product availability - notifies remaining subscribers
RedMI.SetAvailability("Available");

Workflow:

  1. Subject Creation: Product is created with initial "Out Of Stock" status
  2. Observer Registration: Users subscribe to product notifications
  3. State Change: Product availability changes to "Available"
  4. Notification: All registered observers receive update notifications
  5. Observer Removal: Users can unsubscribe from notifications

Benefits:

  • Establishes loose coupling between subject and observers
  • Supports broadcast communication
  • Allows dynamic relationships between objects
  • Follows Open/Closed Principle - can add new observers without modifying subject
  • Enables event-driven programming model