设计模式学习-Memento(备忘录)
意图:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可将该对象恢复到原先保存的状态。
一个备忘录(Memento)是一个对象,它存储另一个对象在某个瞬间的内部状态,而后者称为备忘录的原发器(Originator)
适用性:
必须保持某个对象在某个时刻的状态
如果一个用接口来让其它对象这节得到这些状态,将会暴露对象的实现细节并破坏对象的封装性
示例图:
示例代码:
//线条类
class CLine
{
public:
CLine(LineState
STATE);
public:
~CLine(void);
public:
//移动到目标位置
void
MoveTo(POINT start,POINT end)
{
CSolver* pSolver =
CSolver::Instance();
CLineMemento *pMem =
pSolver->CreateMemento();
pMem->m_State =
m_State;
_tprintf(_T("Line move from (%d:%d-%d:%d) to
(%d:%d-%d:%d)/n"),
m_State.Start.x,m_State.Start.y,m_State.End.x,m_State.End.y,start.x,start.y,end.x,end.y);
m_State.Start = start;
m_State.End = end;
}
//撤销移动
void UnDoMoveTo()
{
LineState state =
RestoreMemento();
_tprintf(_T("Line un move from (%d:%d-%d:%d) to
(%d:%d-%d:%d)/n"),
m_State.Start.x,m_State.Start.y,m_State.End.x,m_State.End.y,state.Start.x,state.Start.y,state.End.x,state.End.y);
m_State = state;
CSolver* pSolver = CSolver::Instance();
CLineMemento *pMem = pSolver->CreateMemento();
pMem->m_State = m_State;
}
private:
LineState
RestoreMemento()
{
CSolver* pSolver =
CSolver::Instance();
CLineMemento *pMem =
pSolver->CreateMemento();
return pMem->m_State;
}
private:
LineState m_State;
};
//线条备忘类
class CLineMemento
{
friend class CLine;
public:
CLineMemento();
public:
~CLineMemento(void);
protected:
LineState m_State;
};
//相对简单的Solver
class CSolver
{
private:
CSolver(void);
private:
~CSolver(void);
public:
CLineMemento* CreateMemento()
{
if(m_pMem == NULL)
{
m_pMem = new CLineMemento();
}
return m_pMem;
}
public:
static CSolver* Instance()
{
return
&m_PInstance;
}
private:
static CSolver m_PInstance;
CLineMemento* m_pMem;
};
也可以支持链表形式的备忘录,用于支持撤销多个操作……