1
0
Fork 0

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

This commit is contained in:
IvisTang 2026-01-06 23:32:11 +08:00
parent 78d4634cf3
commit 5022b481a4
3 changed files with 221 additions and 0 deletions

80
go/memento/main.go Normal file
View File

@ -0,0 +1,80 @@
package main
import (
"fmt"
)
/*
实例
汤宝宝聘请了一位私人助理帮助他管理日常事务
他负责记录汤宝宝的状态以便在需要时恢复到之前的状态
*/
// 原发器 - 汤宝宝
type Tom struct {
state string
}
func (t *Tom) CreateMemento() *Memento {
m := &Memento{}
m.setState(t.state)
fmt.Println("汤宝宝创建了备忘录,状态为:", t.state)
return m
}
func (t *Tom) RestoreMemento(memento *Memento) {
t.state = memento.GetState()
fmt.Println("汤宝宝恢复了状态:", t.state)
}
// 备忘录
type Memento struct {
state string
}
func (m *Memento) GetState() string {
return m.state
}
func (m *Memento) setState(state string) {
m.state = state
}
// 负责人 - 私人助理
type Assistant struct {
mementos []*Memento
}
func (a *Assistant) Backup(tom *Tom) {
a.mementos = append(a.mementos, tom.CreateMemento())
fmt.Println("私人助理备份了汤宝宝的状态")
}
func (a *Assistant) Undo(tom *Tom) {
if len(a.mementos) == 0 {
fmt.Println("没有备份可供恢复")
return
}
memento := a.mementos[len(a.mementos)-1]
a.mementos = a.mementos[:len(a.mementos)-1]
fmt.Println("私人助理恢复了汤宝宝的状态")
tom.RestoreMemento(memento)
}
func main() {
fmt.Println("============= 备忘录模式 =============")
tom := &Tom{state: "开心"}
fmt.Println("汤宝宝的当前状态:", tom.state)
assistant := &Assistant{}
assistant.Backup(tom)
tom.state = "生气"
fmt.Println("汤宝宝的当前状态:", tom.state)
assistant.Undo(tom)
fmt.Println()
fmt.Println("=========== 备忘录模式结束 ===========")
}

64
python/memento/main.py Normal file
View File

@ -0,0 +1,64 @@
"""实例:
汤宝宝聘请了一位私人助理帮助他管理日常事务
他负责记录汤宝宝的状态以便在需要时恢复到之前的状态
"""
class Tom:
state: str
def __init__(self, state: str) -> None:
self.state = state
def create_memento(self):
m = Memento(self.state)
print(f"汤宝宝创建了备忘录,状态为:{m.get_state()}")
return m
def restore_memento(self, memento):
self.state = memento.get_state()
print(f"汤宝宝恢复了状态:{self.state}")
class Memento:
__state: str
def __init__(self, state: str) -> None:
self.__state = state
def get_state(self):
return self.__state
def set_state(self, state: str):
self.__state = state
class Assistant:
__memento_list = []
def backup(self, tom: Tom):
self.__memento_list.append(tom.create_memento())
def undo(self, tom: Tom):
if not self.__memento_list:
print("没有备份可供恢复")
return
memento = self.__memento_list.pop()
print("私人助理恢复了汤宝宝的状态")
tom.restore_memento(memento)
if __name__ == "__main__":
print("============= 备忘录模式 =============")
tom = Tom("开心")
print(f"汤宝宝的当前状态:{tom.state}")
assistant = Assistant()
assistant.backup(tom)
tom.state = "生气"
print(f"汤宝宝的当前状态:{tom.state}")
assistant.undo(tom)
print("\n=========== 备忘录模式结束 ===========")

77
ts/src/memento/index.ts Normal file
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=========== 备忘录模式结束 ===========");
})();