Python: Memento Pattern
GeovinDuMemento.py
# 备忘录模式 Memento Pattern GeovinDuMemento.py # class Memento: def __init__(self, value): self.state = value def SetState(self, value): self.state = value def GetState(self): return self.state class Originator: def SetState(self, value): self.state = value def GetState(self): return self.state def CreateMemento(self): return Memento(self.state) def SetMemento(self, memento): print("返回上一状态.") self.state = memento.GetState() class Caretaker: def __init__(self, originatorObj): self.memento = None self.origin = originatorObj def Execute(self): self.memento = self.origin.CreateMemento() self.origin.SetState(0) def Unexecute(self): self.origin.SetMemento(self.memento)
main.py 调用
# 备忘录模式 Memento Pattern originator = GeovinDuMemento.Originator() originator.SetState(1) print("状态值为: ", originator.GetState()) caretaker = GeovinDuMemento.Caretaker(originator) caretaker.Execute() print("状态值为: ", originator.GetState()) caretaker.Unexecute() print("状态值为: ", originator.GetState())
输出:
状态值为: 1 状态值为: 0 返回上一状态. 状态值为: 1
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)