其他分享
首页 > 其他分享> > 【设计模式】备忘录模式

【设计模式】备忘录模式

作者:互联网

class Memento:

    def __init__(self, state):
        self.state = state

    def set_state(self, state):
        self.state = state

    def get_state(self):
        return self.state

class Caretaker:

    def __init__(self):
        self.memento_table = {}

    def set_memento(self, key, memento):
        self.memento_table[key] = memento

    def get_memento(self, key):
        return self.memento_table[key]


class Orignator:

    def set_state(self, state):
        self.state = state

    def get_state(self):
        return self.state

    def create_memento(self):
        return Memento(self.state)

    def restore_memento(self, memento):
        self.set_state(memento.get_state())

if __name__ == '__main__':
    o = Orignator()
    c = Caretaker()

    o.set_state({'data':'s1'})
    print('初始状态',o.get_state())
    c.set_memento(1,o.create_memento())
    o.set_state({'data':'s2'})
    print('新的状态',o.get_state())

    c.set_memento(2,o.create_memento())
    o.restore_memento(c.get_memento(1))
    print(o.get_state())

    print(c.memento_table)

标签:__,set,self,模式,备忘录,state,def,设计模式,memento
来源: https://blog.csdn.net/qq_44647926/article/details/122494713