实现中介者模式示例,添加中介者、同事类及具体实现,增强代码可读性

This commit is contained in:
2026-01-06 18:29:49 +08:00
parent f579b1a5cc
commit 78d4634cf3
3 changed files with 291 additions and 0 deletions
+98
View File
@@ -0,0 +1,98 @@
/*
实例:
汤宝宝一时想不开,当了房产中介。
他负责把房东和租客撮合在一起,帮他们达成租房协议。
*/
// 抽象中介者
interface Mediator {
register(colleague: Colleague): void;
notify(sender: Colleague, event: string): void;
}
// 抽象同事
interface Colleague {
send(event: string): void;
receive(event: string): void;
}
// 具体中介者
class HousingMediator implements Mediator {
private colleagues: Colleague[];
constructor() {
this.colleagues = [];
}
register(colleague: Colleague): void {
if (!this.colleagues.includes(colleague)) {
this.colleagues.push(colleague);
}
}
notify(sender: Colleague, event: string): void {
for (const colleague of this.colleagues) {
if (colleague !== sender) {
colleague.receive(event);
}
}
}
}
// 具体同事 - 房东
class Landlord implements Colleague {
private mediator: Mediator;
private name: string;
constructor(mediator: Mediator, name: string) {
this.mediator = mediator;
this.name = name;
this.mediator.register(this);
}
send(event: string): void {
console.log(`房东${this.name}发布信息: ${event}`);
this.mediator.notify(this, event);
}
receive(event: string): void {
console.log(`房东${this.name}收到通知: ${event}`);
}
}
// 具体同事 - 租客
class Tenant implements Colleague {
private mediator: Mediator;
private name: string;
constructor(mediator: Mediator, name: string) {
this.mediator = mediator;
this.name = name;
this.mediator.register(this);
}
send(event: string): void {
console.log(`租客${this.name}发布需求: ${event}`);
this.mediator.notify(this, event);
}
receive(event: string): void {
console.log(`租客${this.name}收到通知: ${event}`);
}
}
(function () {
console.log("============= 中介者模式 =============");
const mediator = new HousingMediator();
const landlord1 = new Landlord(mediator, "张三");
const landlord2 = new Landlord(mediator, "李四");
const tenant1 = new Tenant(mediator, "王五");
const tenant2 = new Tenant(mediator, "赵六");
landlord1.send("张三有一套两室一厅的房子出租,月租2000元。");
console.log("-----");
tenant1.send("王五需要一套三室的房子,预算3000元/月。");
console.log("\n=========== 中介者模式结束 ===========");
})();