笔记:Gof设计模式--Memento

1、意图

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

 

2、适应性

  Use the Memento pattern when

  •  a snapshot of (some portion of) an object's state must be saved sothat it can be restored to that state later, and
  •  a direct interface to obtaining the state would exposeimplementation details and break the object's encapsulation.

3、结构

 

 

4、示例代码

  Weuse MoveCommand objects (see Command (263)) to (un)dothe translation of a graphical object from one position to another.

class Graphic; 
// base class for graphical objects in the graphical edito
 
class MoveCommand { 
public: 
    MoveCommand(Graphic* target, const Point& delta); 
    void Execute(); 
    void Unexecute(); 
private: 
    ConstraintSolverMemento* _state; 
    Point _delta; 
    Graphic* _target; 
}; 
 

class ConstraintSolver { 
public: 
static ConstraintSolver* Instance(); 
void Solve(); 
void AddConstraint( 
Graphic* startConnection, Graphic* endConnection         
); 
void RemoveConstraint( 
Graphic* startConnection, Graphic* endConnection 
); 
ConstraintSolverMemento* CreateMemento(); 
void SetMemento(ConstraintSolverMemento*); 
private: 
// nontrivial state and operations for enforcing 
// connectivity semantics    }; 
 
class ConstraintSolverMemento { 
public: 
virtual ~ConstraintSolverMemento(); 
private: 
friend class ConstraintSolver; 
ConstraintSolverMemento(); 
// private constraint solver state 
}; 

// implement MoveCommand membersExecute and Unexecute as follows: 
void MoveCommand::Execute () { 
ConstraintSolver* solver = ConstraintSolver::Instance(); 
_state = solver->CreateMemento();  
// create a memento 
_target->Move(_delta); 
solver->Solve(); 
} 
 
void MoveCommand::Unexecute () { 
ConstraintSolver* solver = ConstraintSolver::Instance(); 
_target->Move(-_delta); 
solver->SetMemento(_state);  
// restore solver state 
solver->Solve(); 
} 


 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值