稍微有点感冒,鼻子就难受的不行,都怪那个倒霉的周二没有把头发吹干。不过还是把这几行代码写完吧。。。 。。。
今天来看看备忘录模式.
UML图很简单:
代码也不是很复杂,下面是C++实现
/*
* Copyright (c) 2017 initm.com All rights reserved.
* 作者: Stupid
* 描述: 备忘录模式
* 完成时间: 2017-11-2 20:37
*/
#include <QCoreApplication>
#include <iostream>
#include <string>
//备忘录类
class Memento
{
private:
std::string state;
public:
Memento(const std::string& state): state(state){
}
std::string GetState(){
return state;
}
};
//发起人类
class Originator
{
private:
std::string state;
public:
std::string GetState(){
return state;
}
void SetState(const std::string& state){
this->state = state;
}
Memento* CreateMemento(){
return new Memento(state);
}
void SetMemento(Memento* memento){
if(nullptr == memento){
return ;
}
state = memento->GetState();
}
void Show(){
std::cout << "State=" << state << std::endl;
}
};
//管理者类
class Caretaker
{
private:
Memento* memento = nullptr;
public:
Memento* GetMemento(){
return memento;
}
void SetMemento(Memento* memento){
if(nullptr != this->memento){
delete this->memento;
}
this->memento = memento;
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Originator* originator = new Originator;
originator->SetState("on");
originator->Show();
Caretaker* caretaker = new Caretaker;
caretaker->SetMemento(originator->CreateMemento());
originator->SetState("off");
originator->Show();
originator->SetMemento(caretaker->GetMemento());
originator->Show();
delete caretaker;
delete originator;
return a.exec();
}
通过创建一个备忘录,我们可以再以后的某个时刻恢复以前的状态,这好像是到目前为止第一个没有用到继承的模式

