Python设计模式之备忘录模式原理与用法详解

yipeiwu_com7年前Python基础

本文实例讲述了Python设计模式之备忘录模式原理与用法。分享给大家供大家参考,具体如下:

备忘录模式(Memento Pattern):不破坏封装性的前提下捕获一个对象的内部状态,并在该对象之外保存这个状态,这样已经后就可将该对象恢复到原先保存的状态

下面是一个备忘录模式的demo:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Andy'
"""
大话设计模式
设计模式——备忘录模式
备忘录模式(Memento Pattern):不破坏封装性的前提下捕获一个对象的内部状态,并在该对象之外保存这个状态,这样已经后就可将该对象恢复到原先保存的状态
"""
# 发起人类
class Originator(object):
  def __init__(self, state):
    self.state = state
  def create_memento(self):
    return Memento(self.state)
  def set_memento(self, memento):
    self.state = memento.state
  def show(self):
    print "当前状态 ", self.state
# 备忘录类
class Memento(object):
  def __init__(self, state):
    self.state = state
# 管理者类
class Caretaker(object):
  def __init__(self,memento):
    self.memento = memento
if __name__ == "__main__":
  # 初始状态
  originator = Originator(state='On')
  originator.show()
  # 备忘录
  caretaker = Caretaker(originator.create_memento())
  # 修改状态
  originator.state = 'Off'
  originator.show()
  # 复原状态
  originator.set_memento(caretaker.memento)
  originator.show()

运行结果:

当前状态  On
当前状态  Off
当前状态  On

上面的类的设计如下图:

Originator(发起人):负责创建一个备忘录Memento,用以记录当前时刻它的内部状态,并可使用备忘录恢复内部状态,Originator可根据需要决定Memento存储Originator的那些内部状态

Memento(备忘录):负责存储Originator对象的内部状态,并可防止Originator以外的其他对象访问备忘录Memento

Caretaker(管理者):负责保存好备忘录Memento,不能对备忘录的内容进行操作或检查

更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

python模拟登录百度贴吧(百度贴吧登录)实例

python模拟登录百度贴吧(百度贴吧登录)实例

 复制代码 代码如下:# -*- coding:utf-8 -*-# python3.3.3 import sys,time,re,urllib.parse,u...

Python的Bottle框架中实现最基本的get和post的方法的教程

Python的Bottle框架中实现最基本的get和post的方法的教程

1、GET方式:    # -*- coding: utf-8 -*- #!/usr/bin/python # filename: GETPOST_test.p...

django中forms组件的使用与注意

forms组件 django框架提供了一个Form类,来进行web开发中的表单提交数据的处理工作。 导入相关模块 from django import forms from dja...

SublimeText 2编译python出错的解决方法(The system cannot find the file specified)

[Error 2] The system cannot find the file specified 解决方法:1.环境变量path添加:C:\Python32\Tools\Scrip...

新年快乐! python实现绚烂的烟花绽放效果

新年快乐! python实现绚烂的烟花绽放效果

做了一个Python的小项目。利用了一点python的可视化技巧,做出烟花绽放的效果,文章的灵感来自网络上一位大神。 一.编译环境 Pycharm 二.模块 1.tkinter:这个...