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();
}