Mediator
Posted by Dustin Boston .
CAUTION
Construction Area
Watch out for:
- Broken code
- No comments
- Partial examples
- Missing tests
Source Code Listing
code.ts
type Mediator = {
colleagueChanged(colleague: Colleague): void;
};
abstract class Colleague {
constructor(protected mediator: Mediator) {}
changed(): void {
this.mediator.colleagueChanged(this);
}
abstract event(): void; // Abstract event method
}
class ConcreteColleague1 extends Colleague {
event(): void {
this.changed();
}
}
class ConcreteColleague2 extends Colleague {
event(): void {
this.changed();
}
}
class ConcreteMediator implements Mediator {
private colleague1: ConcreteColleague1 | undefined = undefined; // Initialize to null
private colleague2: ConcreteColleague2 | undefined = undefined; // Initialize to null
createColleagues(): void {
this.colleague1 = new ConcreteColleague1(this);
this.colleague2 = new ConcreteColleague2(this);
this.colleague1.event();
this.colleague2.event();
}
colleagueChanged(colleague: Colleague): void {
if (colleague instanceof ConcreteColleague1) {
console.log("colleague1 changed");
} else if (colleague instanceof ConcreteColleague2) {
console.log("colleague2 changed");
}
}
}
const example = {
run(): void {
const m = new ConcreteMediator();
m.createColleagues();
},
};
example.run();