备忘录模式(Memento模式):是行为模式之一。它的作用是保持某一个对象的转态,并且在需要的时候,恢复对象以前的状态。
在备忘录模式中主要涉及到了三个类:
- originator这个类是需要被保存状态的类;
- Memento该类的对象由originator创建,主要用来保存originator的内部状态。
- Careataker负责在需要的情况下去保存或者恢复originator的状态。
Person这个类作为originator类是需要保存状态的类,Memento主要作用用来保存originator类的状态。Caretaker类主要负责控制Memento类,其实说白了也就是对Memento类又封装了一层。
#include <iostream>
#include <string>
using namespace std;
class Memento
{
public:
Memento(string name,int age)
{
this->m_name = name;
this->m_age = age;
}
string getName()
{
return m_name;
}
int getAge()
{
return m_age;
}
void setName(string name)
{
this->m_name = name;
}
void setAge(int age)
{
this->m_age = age;
}
private:
string m_name;
int m_age;
};
class Person
{
public:
Person(string name,int age)
{
this->m_name = name;
this->m_age = age;
}
string getName()
{
return this->m_name;
}
int getAge()
{
return this->m_age;
}
void setName(string name)
{
this->m_name = name;
}
void setAge(int age)
{
this->m_age = age;
}
Memento* createMemento()
{
return new Memento(m_name,m_age);
}
void setMemento(Memento *memento)
{
this->m_name = memento->getName();
this->m_age = memento->getAge();
}
void printT()
{
cout<<m_name<<":"<<m_age<<endl;
}
private:
string m_name;
int m_age;
};
class Caretaker
{
public:
Caretaker(Memento *memento)
{
this->m_memento = memento;
}
Memento* getMemento()
{
return this->m_memento;
}
void setMemento(Memento *memento)
{
this->m_memento = memento;
}
private:
Memento *m_memento;
};
int main()
{
Person *person = new Person("小高",27);
person->printT();
Caretaker *caretaker = new Caretaker(person->createMemento());
person->setName("小秦");
person->printT();
person->setMemento(caretaker->getMemento());
person->printT();
delete caretaker;
delete person;
}