class Mediator {
/**
* 一个示例操作
*
* @param colleague 发送消息的同事类
* @param message 消息内容
*/
operate(colleague, message){
throw new Error("This method must be overwritten!");
}
}
class ConcreteMediator extends Mediator {
constructor() {
super();
// 持有的具体同事类
this.firstColleague = new FirstColleague(this),
this.secondColleague = new SecondColleague(this);
}
operate(colleague, message) {
// 同事类之间的交互通过中介者进行。
// 这里只演示了两个同事类。
if(colleague == this.firstColleague){
this.secondColleague.receive(message);
} else if(colleague == this.secondColleague) {
this.firstColleague.receive(message);
}
}
}
class AbstractColleague {
constructor(mediator) {
this._mediator = mediator;
}
send(message) {
throw new Error("This method must be overwritten!");
}
receive(message, sender) {
throw new Error("This method must be overwritten!");
}
}
class FirstColleague extends AbstractColleague{
constructor(mediator) {
super(mediator);
}
// 向中介者发送消息。
send(message){
this.mediator.operate(this, message);
}
// 从中介者接收到的消息。
receive(message){
console.log("First Colleague 收到消息:" + message);
}
}
class SecondColleague extends AbstractColleague {
constructor(mediator) {
super(mediator);
}
// 向中介者发送消息。
send(message) {
//this.mediator.operate(this, message);
}
// 从中介者接收到的消息。
receive(message) {
console.log("Second Colleague 收到消息:" + message);
}
}
// 把同事类注册到中介者
let mediator = new ConcreteMediator();
let firstColleague = new FirstColleague(mediator);
let secondColleague = new SecondColleague(mediator);
// 同事类之间通过中介者交互
firstColleague.send("Hello World");
secondColleague.send("Word Count");
console