Mediator

About

It is like a middle-man or broker (mediator), this pattern help reducing coupling between two or multiple Objects, by intruducing a bus/channel for communication, so that one Object can notify the other Object whenever it has to.

It provides separation of concerns and eliminates code duplication.

circle-info

A Mediator have a relationship of manymanymany \to many, meaning:

  • Many Objects can notify/publish. (One or multiple events)

  • Many Objects can subscribe and react to these events.

circle-check
interface Handler {
    // The Event name
    event: string;
    // What must be executed when this Event happens
    callback: Function
}

class Mediator {
    // The handlers are the interested parties
    handlers: Handler[];
    
    constructor() {
        this.handlers = [];
    }
    
    // Here we register events to the handlers and set what should execute when
    // the event happens.
    register(event: string, callback: Function) {
        this.handlers.push({ event, callback });
    }
    
    // When a notify of a specific event is called, all handlers that subscribed
    // to this event get notified.
    async notify(event: string, data: any) {
        for (const handler of this.handlers) {
            if (handler.event === event) await handler.callback(data);
        }
    }
}

Chaining Usecases Example

In this example, lets suppose that we have these three usecases (FinishRide, ProcessPayment and GenerateInvoice), and the last two should be called after the Ride ends.

To avoid injecting and calling ProcessPayment and GenerateInvoice inside FinishRide class, we use a Mediator to generate the nofication that the Ride ended.

Notify from Application Layer

Notify from Domain Layer

You could be more strict, and state that the Event notification is the Domain Object Ride responsability.

circle-exclamation

For this we can make these changes:

circle-exclamation

Notify from Domain Layer - With Domain Event

It is possible to define the Event, more specifically, as a Domain Event.

Last updated