Published on

[Behavioral] Mediator

Real world example

A general example would be when you talk to someone on your mobile phone, there is a network provider sitting between you and them and your conversation goes through it instead of being directly sent. In this case network provider is mediator.

In plain words

Mediator pattern adds a third party object (called mediator) to control the interaction between two objects (called colleagues). It helps reduce the coupling between the classes communicating with each other. Because now they don't need to have the knowledge of each other's implementation.

Wikipedia says

In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program's running behavior.

Programmatic Example

Here is the simplest example of a chat room (i.e. mediator) with users (i.e. colleagues) sending messages to each other.

First of all, we have the mediator i.e. the chat room

interface ChatRoomMediator {
    showMessage(user: User, message: string)
}

// mediator
export class ChatRoom implements ChatRoomMediator {
    protected message: string;

    showMessage(user: User, message: string) {
        this.message = message
        console.log(`${new Date()} ${user.getName()} ${message}`)
    }

    getMessage(): string{
        return this.message;
    }
}

Then we have our users i.e. colleagues

export class User {
    protected name;
    protected chatMediator;

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

    getName() {
        return this.name
    }

    send(message) {
        this.chatMediator.showMessage(this, message)
    }
}

And the usage

test('test mediator design pattern', () => {
    const mediator = new ChatRoom();

    const john = new User('John Doe', mediator)
    const jane = new User('Jane Doe', mediator)

    john.send('Hello')
    expect(mediator.getMessage()).toEqual('Hello')
    jane.send('Hi')
    expect(mediator.getMessage()).toEqual('Hi')
})

References