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
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.
This implementation demonstrates a product availability notification system where users can subscribe to get notified when a product becomes available:
- 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
ISubject- Subject interface with observer management methodsIObserver- Observer interface with Update(string availability) methodSubject- Concrete subject that maintains product state (ProductName, ProductPrice, Availability)Observer- Concrete observer representing users with UserName property
// 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");- Subject Creation: Product is created with initial "Out Of Stock" status
- Observer Registration: Users subscribe to product notifications
- State Change: Product availability changes to "Available"
- Notification: All registered observers receive update notifications
- Observer Removal: Users can unsubscribe from notifications
- 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