This pattern allows you to define a separate object (the mediator) that controls the communication between a set of objects (the colleagues). This can be useful when you want to reduce the dependency between objects, and when you want to centralize the control of communication between objects in a single place.
Here is an example of the mediator pattern in JavaScript:
}
colleague.
}
colleague.
}
});
}
}
}
}
}
}
}
mediator.
mediator.
mediator.
colleague1.
// Output:
// Colleague 1 sends message: 'Hello, World!'.
// Colleague 2 receives message: 'Hello, World!'.
// Colleague 3 receives message: 'Hello, World!'.
colleague2.
// Output:
// Colleague 2 sends message: 'Hi, there!'.
// Colleague 1 receives message: 'Hi, there!'.
// Colleague 3 receives message: 'Hi, there!'.
colleague3.
// Output:
// Colleague 3 sends message: 'How are you?'.
// Colleague 1 receives message: 'How are you?'.
// Colleague 2 receives message: 'How are you?'.
In this example, the Mediator class is a class that controls the communication between a set of Colleague objects, and the Colleague class is a class that represents an object that communicates with other objects through the mediator. The Mediator class has a register() method for registering colleagues and a send() method for sending messages to registered colleagues.
The Colleague class has a setMediator() method for setting the mediator and a send() method for sending messages through the mediator.
To use the mediator pattern, we create an instance of the Mediator class, and then create instances of the Colleague class. We register the colleague objects with the mediator using the register() method, and then set the mediator for the colleague objects using the send() method of the Colleague class to send messages through the mediator.