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.
Depending on how you use it, Mediator can also act as Mediator.
Ex.:
If many different Objects generate events to many interested parties, it acts as
Mediator.If only one Object generate events to many different parties, it acts as
Observer.
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.
We avoid making the finish() method from Ride return the Event data, because otherwise, the method return type is tied to Events.
For this we can make these changes:
As a curiosity:
When making the Ride extend Mediator, the Mediator is actually acting as an Mediator, because it has a relationship of , since only the Ride Object can notify (create events).
Notify from Domain Layer - With Domain Event
Domain EventIt is possible to define the Event, more specifically, as a Domain Event.
Last updated