Definition
Concept
Observer: a behavioral design pattern. Purpose: defines a one-to-many dependency between objects. Effect: when subject changes state, all dependents (observers) notified and updated automatically. Decoupling: subject unaware of observer concrete classes.
Scope
Category: behavioral pattern in software design. Domain: event-driven systems, UI frameworks, distributed systems. Key principle: separation of concerns via publish-subscribe mechanism.
Historical Context
Origin: described in "Design Patterns" by Gamma et al., 1994. Prevalence: foundational in MVC architectures and reactive programming.
Motivation
Problem Statement
Tight coupling: subjects directly managing dependents leads to fragile, hard-to-maintain code. Need: dynamic, flexible communication without explicit dependencies.
Use Case Scenarios
Examples: GUI event listeners, real-time data feeds, distributed state synchronization, logging frameworks reacting to state changes.
Goals
Objectives: enable runtime subscription/unsubscription, promote loose coupling, ensure consistency between subject and observers.
Structure
Class Diagram
Core components: Subject interface (attach, detach, notify), ConcreteSubject (maintains state), Observer interface (update method), ConcreteObserver (reacts to updates).
Relationships
Subject maintains list of observers. Observers register/unregister themselves. Notification triggered by state change.
Sequence
State change → Subject calls notify() → Observers’ update() called → Observers query subject or receive data.
Participants
Subject
Role: provides interface for attaching, detaching, notifying observers. Maintains state relevant to observers.
Observer
Role: defines update interface for subjects to call when notifying changes.
ConcreteSubject
Role: stores state of interest, triggers notifications on state change.
ConcreteObserver
Role: maintains reference to ConcreteSubject, updates state to keep consistent.
Collaborations
Registration
Observers register with subjects via attach method. Subjects add observers to internal collection.
Notification
On state change, subject calls notify which invokes update on all registered observers.
State Synchronization
Observers retrieve updated state from subject or receive it as argument in update method.
Consequences
Benefits
Loose coupling, dynamic subscriptions, improved modularity, reusable components, scalability in event-driven systems.
Drawbacks
Potential memory leaks if observers not detached, unpredictable update order, overhead in notifying many observers.
Trade-offs
Balance between flexibility and complexity. Requires careful observer lifecycle management.
Implementation
Basic Algorithm
class Subject { private observers = []; attach(observer) { observers.push(observer); } detach(observer) { observers = observers.filter(o => o !== observer); } notify() { observers.forEach(observer => observer.update()); }}class ConcreteSubject extends Subject { state; setState(ne