The Observer Pattern inTypescript

Rob Paul
2 min readFeb 1, 2023

The Observer Pattern in Typescript is a software design pattern where an object, known as the subject, maintains a list of its dependent objects (observers) and notifies them of any state changes.

In a nutshell, the Observer decouples senders and receivers.

What are the use cases for:

  1. User Interfaces: In the context of User Interfaces, there may be instances where multiple components require updates in response to changes in the state of another component.
  2. Event Handling: In the context of Event Handling, there may be situations where multiple objects need to be informed upon the occurrence of an event, such as a button click.
  3. Game Development: In the context of Game Development, there may be situations where multiple objects require notification of changes in the state of another object, such as changes to the score or game state.

For example in the case of Social Media Applications, there may be instances where multiple users require notification of updates to a post or changes in its state.

class Post {
private subscribers: User[];
private state: string;

constructor(state: string) {
this.subscribers = [];
this.state = state;
}

subscribe(user: User) {
this.subscribers.push(user);
}

setState(state: string) {
this.state = state;
this.notifySubscribers();
}

private notifySubscribers() {
this.subscribers.forEach(user => user.notify(this));
}
}

class User {
name: string;

constructor(name: string) {
this.name = name;
}

notify(post: Post) {
console.log(`User ${this.name} has been notified of a change to the post: ${post.state}`);
}
}

const post = new Post("Initial state");
const user1 = new User("John");
const user2 = new User("Jane");

post.subscribe(user1);
post.subscribe(user2);

post.setState("Updated state");

// Output:
// User John has been notified of a change to the post: Updated state
// User Jane has been notified of a change to the post: Updated state

The Post class acts as the subject in the pattern and maintains a list of subscribers in the subscribers array. The setState method updates the post’s state and notifies all subscribers through the notifySubscribers method. The User class represents an observer and has a notify method that outputs a message to the console when a user is notified of a change to a post.

The example also demonstrates the use of encapsulation, as the internal details of the Post class are hidden and only a public interface is exposed for other objects to interact with it. This ensures that changes to the internal details of the Post class do not affect other objects that depend on it.

A limitation of the Observer Pattern is that it can lead to an increase in the coupling between objects, which can make the system more complex and harder to maintain. Additionally, if an observer is no longer needed, it may be difficult to remove it from the subject’s list of subscribers, leading to potential memory leaks.

--

--