实现观察者模式示例,添加观察者、目标及具体实现,增强代码可读性
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
实例:
|
||||
汤宝宝一时想不开,当了房产中介。
|
||||
一旦片区内有房东发布了新房源信息,他就会第一时间通知所有潜在租客。
|
||||
*/
|
||||
|
||||
// 观察者抽象接口
|
||||
interface Observer {
|
||||
update(): void;
|
||||
}
|
||||
|
||||
// 目标抽象接口
|
||||
interface Subject {
|
||||
attach(observer: Observer): void;
|
||||
detach(observer: Observer): void;
|
||||
notify(): void;
|
||||
}
|
||||
|
||||
// 具体目标类
|
||||
class HousingAgency implements Subject {
|
||||
private observers: Observer[];
|
||||
|
||||
constructor() {
|
||||
this.observers = [];
|
||||
}
|
||||
|
||||
attach(observer: Observer): void {
|
||||
const isExist = this.observers.includes(observer);
|
||||
if (isExist) {
|
||||
return console.log("Observer has been attached already.");
|
||||
}
|
||||
this.observers.push(observer);
|
||||
}
|
||||
|
||||
detach(observer: Observer): void {
|
||||
const observerIndex = this.observers.indexOf(observer);
|
||||
if (observerIndex === -1) {
|
||||
return console.log("Nonexistent observer.");
|
||||
}
|
||||
this.observers.splice(observerIndex, 1);
|
||||
}
|
||||
|
||||
notify(): void {
|
||||
console.log("房产中介通知了所有租客。");
|
||||
for (const observer of this.observers) {
|
||||
observer.update();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 具体观察者类
|
||||
class TenantObs implements Observer {
|
||||
private name: string;
|
||||
|
||||
constructor(name: string) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
update(): void {
|
||||
console.log(`租客${this.name}收到了房源更新通知。`);
|
||||
}
|
||||
}
|
||||
|
||||
(function () {
|
||||
console.log("============= 观察者模式 =============");
|
||||
const agency = new HousingAgency();
|
||||
const tenant1 = new TenantObs("小明");
|
||||
const tenant2 = new TenantObs("小红");
|
||||
console.log("小红和小明订阅了房产中介的房源信息。");
|
||||
agency.attach(tenant1);
|
||||
agency.attach(tenant2);
|
||||
console.log("房源上新了!");
|
||||
agency.notify();
|
||||
|
||||
console.log("-----");
|
||||
console.log("小红不想再接收房源信息,退订了。");
|
||||
agency.detach(tenant2);
|
||||
console.log("又有新房源了!");
|
||||
agency.notify();
|
||||
|
||||
console.log("\n=========== 观察者模式结束 ===========");
|
||||
})();
|
||||
Reference in New Issue
Block a user