实现备忘录模式示例,添加原发器、备忘录及负责人类,增强代码可读性

This commit is contained in:
2026-01-06 23:32:11 +08:00
parent 78d4634cf3
commit 5022b481a4
3 changed files with 221 additions and 0 deletions
+77
View File
@@ -0,0 +1,77 @@
/*
实例:
汤宝宝聘请了一位私人助理,帮助他管理日常事务。
他负责记录汤宝宝的状态,以便在需要时恢复到之前的状态。
*/
class Tom {
state: string;
constructor(state: string) {
this.state = state;
}
createMemento(): Memento {
console.log(`汤宝宝创建了备忘录,状态为: ${this.state}`);
return new Memento(this.state);
}
restoreMemento(memento: Memento): void {
this.state = memento.getState();
console.log(`汤宝宝恢复了状态: ${this.state}`);
}
}
class Memento {
private state: string;
constructor(state: string) {
this.state = state;
}
getState(): string {
return this.state;
}
setState(state: string): void {
this.state = state;
}
}
class Assistant {
private mementos: Memento[];
constructor() {
this.mementos = [];
}
backup(tom: Tom): void {
const memento = tom.createMemento();
this.mementos.push(memento);
console.log("私人助理备份了汤宝宝的状态");
}
undo(tom: Tom): void {
if (this.mementos.length === 0) {
console.log("没有备份可供恢复");
return;
}
const memento = this.mementos.pop()!;
console.log("私人助理恢复了汤宝宝的状态");
tom.restoreMemento(memento);
}
}
(function () {
console.log("============= 备忘录模式 =============");
const tom = new Tom("开心");
console.log(`汤宝宝的当前状态:${tom.state}`);
const assistant = new Assistant();
assistant.backup(tom);
tom.state = "生气";
console.log(`汤宝宝的当前状态:${tom.state}`);
assistant.undo(tom);
console.log("\n=========== 备忘录模式结束 ===========");
})();