0
点赞
收藏
分享

微信扫一扫

c++设计模式-----备忘录模式Mmento


备忘录模式:

      备忘录模式很简单啊,就是备份之前的状态。在之后恢复这个状态。

再来看在设计模式中是怎么定义的:

意图:

在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。

适用性:

必须保存一个对象在某一个时刻的(部分)状态, 这样以后需要时它才能恢复到先前的状态。

如果一个用接口来让其它对象直接得到这些状态,将会暴露对象的实现细节并破坏对象的封装性。

c++设计模式-----备忘录模式Mmento_Memento模式

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Originator;
class Memento
{
friend Originator;
public:
Memento(){}
Memento(string st1, string st2) :m_state1(st1), m_state2(st2){}
Memento GetState()
{
return *this;
}
void SetState(const Memento &memento)
{
m_state1 = memento.m_state1;
m_state1 = memento.m_state2;
}

private:
string m_state1;
string m_state2;
};

class Originator
{
public:
Originator(){}
Originator(string st1, string st2) :m_state1(st1), m_state2(st2){}

Memento SetMemento()
{
Memento save;
save.m_state1 = m_state1;
save.m_state2 = m_state2;
return save;
}

void CreatMemento(const Memento &m)
{
m_state1 = m.m_state1;
m_state2 = m.m_state1;
}

void show_state()
{
cout << m_state1 << " " << m_state2 << endl;
}

void chang_status(string st1, string st2)
{
m_state1 = st1;
m_state2 = st2;
}

private:
string m_state1;
string m_state2;
};

class Caretaker
{
public:
Caretaker(){}
void Save(Memento &menento) { vec_memento.push_back(menento); }
Memento get_state(int idx)
{
return vec_memento[idx];
}
private:
vector<Memento> vec_memento;
};

int main()
{
Caretaker caretake;
Originator originalor("chen", "xun");//初始状态
originalor.show_state();
caretake.Save(originalor.SetMemento());//保存初始状态

originalor.chang_status("zte", "company");//改变状体
originalor.show_state();


originalor.CreatMemento(caretake.get_state(0));//恢复状态
originalor.show_state();


return 0;
}



举报

相关推荐

0 条评论