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

  

posted @ 2022-10-27 22:28  ®Geovin Du Dream Park™  阅读(62)  评论(0编辑  收藏  举报