Beginner LevelSoftware Engineering Principles
What is the Observer Pattern and how does event-driven pub/sub communication work?
❓ Interview Prompt: Explain the Observer Behavioral Pattern, Subject/Observer contracts, dynamic event listener subscription, and decoupling event producers.
The Observer Pattern defines a one-to-many dependency relationship between objects so that when one object (Subject) changes state, all its dependent Observers are notified and updated automatically:
Key Advantage:
Decouples event publishers from event subscribers. The Subject maintains a list of dynamic observers without knowing their concrete implementation details.
Code Implementation Example
typescript
type Observer = (data: string) => void;
class EventEmitter {
private observers: Observer[] = [];
subscribe(fn: Observer) { this.observers.push(fn); }
notify(data: string) { this.observers.forEach(fn => fn(data)); }
}
const newsFeed = new EventEmitter();
newsFeed.subscribe(msg => console.log('Observer 1:', msg));
newsFeed.notify('New Article Published');💡Implementing the Observer pattern with a lightweight EventEmitter in TypeScript.
🎯 Interview Key Takeaway
Use the Observer pattern to decouple event sources from dynamic event listeners.
#Observer#PubSub#Design Patterns#Beginner
Back to all Software Engineering Principles Questions→