设计模式23:Memento Pattern (备忘录模式)

本文介绍了备忘录设计模式的概念及应用,通过示例代码详细解释了如何在不违反封装性的前提下,保存和恢复对象的内部状态。适用于需要撤销操作、事务回滚等场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

英文原文:http://www.dofactory.com/Patterns/PatternMemento.aspx

一、Memento Pattern (备忘录模式)

Define:Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.

定义:在不违反封装性,捕获和使得一个对象的内状态具体化,以至于这个对象可以被存储于这个状态之后。

二、UML类图

memento

  • Memento  (Memento)
    • stores internal state of the Originator object. The memento may store as much or as little of the originator's internal state as necessary at its originator's discretion.
    • protect against access by objects of other than the originator. Mementos have effectively two interfaces. Caretaker sees a narrow interface to the Memento -- it can only pass the memento to the other objects. Originator, in contrast, sees a wide interface, one that lets it access all the data necessary to restore itself to its previous state. Ideally, only the originator that produces the memento would be permitted to access the memento's internal state.
  • Originator  (SalesProspect)
    • creates a memento containing a snapshot of its current internal state.
    • uses the memento to restore its internal state
  • Caretaker  (Caretaker)
    • is responsible for the memento's safekeeping
    • never operates on or examines the contents of a memento.

  • 三、Memento Pattern (备忘录模式)实例代码

    四、使用备忘录模式的实例代码

    This real-world code demonstrates the Memento pattern which temporarily saves and then restores the SalesProspect's internal state.

    临时保存和恢复SalesProspect的内部状态

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值