设计模式学习笔记(二十)——Memento备忘录
2007-04-29 08:53
633 查看
十八、Memento(备忘录)
情景举例:
捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
代码示例:
个人理解:
备忘录模式主要由原发器和备忘录构成。主要特点是备忘录对原发器是宽接口,而对其他对象是窄接口。另外,也应该找个适当的地方存储备忘录。(说实话,这个例子不太明了,我仍旧有些地方不太明白。)
情景举例:
捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
代码示例:
classGraphic;
//baseclassforgraphicalobjectsinthegraphicaleditor
/*原发器的接口。注意:这是个Singleton模式
*/
classConstraintSolver{
public:
staticConstraintSolver*Instance();
/*
*/
voidSolve();
voidAddConstraint(
Graphic*startConnection,Graphic*endConnection
);
voidRemoveConstraint(
Graphic*startConnection,Graphic*endConnection
);
/*
*/
ConstraintSolverMemento*CreateMemento();
voidSetMemento(ConstraintSolverMemento*);
private:
//nontrivialstateandoperationsforenforcing
//connectivitysemantics
};
/*备忘录的接口。将原发器申明为友元是为了对原发器提供宽接口,而对其他
对象只提供窄接口
*/
classConstraintSolverMemento{
public:
virtual~ConstraintSolverMemento();
private:
friendclassConstraintSolver;
ConstraintSolverMemento();
//privateconstraintsolverstate
};
/*一个使用备忘录的Commond模式,记忆了状态以供撤销。
*/
classMoveCommand{
public:
MoveCommand(Graphic*target,constPoint&delta);
voidExecute();
voidUnexecute();
private:
ConstraintSolverMemento*_state;
Point_delta;
Graphic*_target;
};
/*在执行的时候产生一个备忘录。Solve方法解释由AddConstraint添加的约
束(不太明白)。
*/
voidMoveCommand::Execute(){
ConstraintSolver*solver=ConstraintSolver::Instance();
_state=solver->CreateMemento();//createamemento
_target->Move(_delta);
solver->Solve();
}
/*在撤销的时候从备忘录中恢复状态。
*/
voidMoveCommand::Unexecute(){
ConstraintSolver*solver=ConstraintSolver::Instance();
_target->Move(-_delta);
solver->SetMemento(_state);//restoresolverstate
solver->Solve();
}
/*
*/
个人理解:
备忘录模式主要由原发器和备忘录构成。主要特点是备忘录对原发器是宽接口,而对其他对象是窄接口。另外,也应该找个适当的地方存储备忘录。(说实话,这个例子不太明了,我仍旧有些地方不太明白。)
相关文章推荐
- HeadFirst 设计模式学习笔记22-- 备忘录(Memento)模式拾零
- 设计模式学习笔记二十——Memento模式
- 设计模式学习笔记--Memento 备忘录模式
- 设计模式学习笔记(十七)—Memento备忘录模式
- 【HeadFirst 设计模式学习笔记】21 备忘录(Memento)模式拾零
- 设计模式学习笔记十九:备忘录模式
- 步步为营 .NET 设计模式学习笔记 二十二、Memento(备望录模式)
- 设计模式笔记--行为型模式之六--Memento 备忘录
- java 设计模式 学习笔记 (14) 备忘录模式
- 设计模式学习笔记二十:解释器模式
- 步步为营 .NET 设计模式学习笔记 二十、Mediator(中介者模式)
- 设计模式学习笔记——备忘录模式
- 设计模式学习笔记——备忘录模式
- 设计模式学习笔记——备忘录模式
- HeadFir st 设计模式学习笔记22-- 备忘录(M emento)模式拾零
- 步步为营 .NET 设计模式学习笔记 二十、Mediator(中介者模式)
- 设计模式学习笔记--备忘录(Mamento)模式
- 设计模式学习笔记(二十)—Visitor访问者模式
- 步步为营 .NET 设计模式学习笔记 二十、Mediator(中介者模式)
- 设计模式学习-Memento(备忘录)