码迷,mamicode.com
首页 > 编程语言 > 详细

python设计模式第二十二天【备忘录模式】

时间:2018-08-12 21:27:55      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:pyc   self   har   nbsp   pre   users   create   nat   应用   

1.应用场景

(1)能保存对象的状态,并能够恢复到之前的状态

2.代码实现

#!/usr/bin/env python
#! _*_ coding:UTF-8 _*_

class Originator(object):
    ‘‘‘这时基本类‘‘‘
    def __init__(self, state):
        self.state = state

    def createMemento(self):
        ‘‘‘创建备忘录‘‘‘
        return Memento(self.state)

    def setMemento(self, memento):
        ‘‘‘从备忘录中恢复‘‘‘
        self.state = memento.state


class Memento(object):
    ‘‘‘这时备忘录类‘‘‘
    def __init__(self, state):
        self.state = state

class Caretaker(object):
    ‘‘‘这时备忘录管理类‘‘‘
    def __init__(self):
        pass

    def setMemento(self, memento):
        ‘‘‘将备忘录作为引用‘‘‘
        self.memento = memento

    def getMemento(self):
        ‘‘‘从管理中获取引用‘‘‘
        return self.memento

if __name__ == "__main__":
    originator = Originator("state1")
    print originator.state

    memento = originator.createMemento()
    caretaker = Caretaker()
    caretaker.setMemento(memento)

    originator.state = "state2"
    print originator.state

    originator.setMemento(caretaker.getMemento())
    print originator.state

结果:

/Users/liudaoqiang/PycharmProjects/numpy/venv/bin/python /Users/liudaoqiang/Project/python_project/day22_memento/memento_test.py
state1
state2
state1

Process finished with exit code 0

 

python设计模式第二十二天【备忘录模式】

标签:pyc   self   har   nbsp   pre   users   create   nat   应用   

原文地址:https://www.cnblogs.com/liuzhiqaingxyz/p/9464101.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!