# Observer

> Objects subscribe to a subject and get notified automatically when it changes — the subject never needs to know who's listening.

- **Category**: Software Design
- **Subcategory**: behavioral
- **Canonical URL**: https://designpattern.fyi/patterns/observer/

---

## Description
**Intent**: Automatically notify any number of interested objects when something changes, without hard-coding who those objects are.

**Context**: You're building a stock ticker, event system, real-time UI updates, or anything where one state change needs to ripple to multiple consumers. Polling is wasteful; direct coupling is brittle.

**Solution**: A Subject maintains a list of Observer subscribers. When state changes, it calls `notify()` on all of them. Observers subscribe and unsubscribe at runtime. The Subject doesn't know or care which Observers are attached — just that they implement `update()`.


## Use Cases
Use for event systems, real-time UI updates, pub/sub messaging, reactive state management, or any scenario where one state change should trigger reactions in multiple places.



## Implementation Example

```javascript
class Subject {
  constructor() { this.observers = []; }
  subscribe(observer) { this.observers.push(observer); }
  unsubscribe(observer) {
    this.observers = this.observers.filter(obs => obs !== observer);
  }
  notify(data) {
    this.observers.forEach(obs => obs.update(data));
  }
}

```



## Trade-offs


### Advantages

- Add new subscriber types without touching the subject's code.

- Subscribe and unsubscribe at runtime — fully dynamic relationships.




### Considerations & Drawbacks

- Notification order is undefined — if subscribers depend on being called in a specific sequence, you'll have subtle bugs.







---
**Reference**: [Original Source](https://refactoring.guru/design-patterns/observer)

