在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
UML结构图:
解析:
Memento模式中封装的是需要保存的状态,当需要恢复的时候才取出来进行恢复。原理很简单,实现的时候需要注意一个地方:窄接口和宽接口。所谓的宽接口就是一般意义上的接口,把对外的接口作为public成员;而窄接口反之,把接口作为private成员,而把需要访问这些接口函数的类作为这个类的友元类,也就是说接口只暴露给了对这些接口感兴趣的类,而不是暴露在外部。下面的实现就是窄实现的方法来实现的。
实现:
1)Memento.h
#ifndef MEMENTO_H #include <string> typedef std::string State; class Memento; class Originator Memento* CreateMemento(); private: // 把Memento的接口函数都设置为私有的,而Originator是它的友元, State m_State; #endif |
2)Memento.cpp
#include "Memento.h" Originator::Originator() } Originator::Originator(const State& rState) } Originator::~Originator() } State Originator::GetState() void Originator::SetState(const State& rState) Memento* Originator::CreateMemento() void Originator::RestoreState(Memento* pMemento) void Originator::PrintState() Memento::Memento(const State& rState) } State Memento::GetState() void Memento::SetState(const State& rState) |
#include "Memento.h" int main() // 创建一个备忘录存放这个原发器的状态 // 通过备忘录把原发器的状态还原到之前的状态 delete pOriginator; return 0; |