模式说明
所谓备忘录模式就是在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样可以在以后将对象恢复到原先保存的状态。
模式结构图
程序示例
说明:游戏存档,恢复
代码:
class Memonto(object): _blood=0 _magic=0 def setBlood(self,blood): self._blood=blood def setMagic(self,magic): self._magic=magic def getBlood(self): return self._blood def getMagic(self): return self._magic class Caretakor(object): _memonto = Memonto() def setMemonto(self,memonto): self._memonto=memonto def getMemonto(self): return self._memonto class Original(object): _blood=0 _magic=0 def __init__(self,blood,magic): self._blood = blood self._magic = magic def setBlood(self,blood): self._blood=blood def setMagic(self,magic): self._magic=magic def display(self): print 'blood:%s magic:%s' % (self._blood,self._magic) def saveMemonto(self): memonto = Memonto() memonto.setBlood(self._blood) memonto.setMagic(self._magic) return memonto def restoreMemonto(self,memonto): self._blood=memonto.getBlood() self._magic=memonto.getMagic() if __name__=="__main__": caretakor = Caretakor() original = Original(100,100) caretakor.setMemonto(original.saveMemonto()) original.display() original.setBlood(20) original.setMagic(30) original.display() original.restoreMemonto(caretakor.getMemonto()) original.display()
运行结果:
参考来源:
http://www.cnblogs.com/chenssy/p/3679190.html
http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html