定义:在不暴露对象实现细节的情况下保存和恢复对象之前的状态。
#include <iostream>
#include <string>
using namespace std;
//备忘录Memento
class Memento
{
private:
string account;
string password;
string telNo;
public:
Memento(string account,string password,string telNo)
{
this->account = account;
this->password = password;
this->telNo = telNo;
}
string getAccount() {
return account;
}
void setAccount(string account) {
this->account = account;
}
string getPassword() {
return password;
}
void setPassword(string password) {
this->password = password;
}
string getTelNo() {
return telNo;
}
void setTelNo(string telNo) {
this->telNo = telNo;
}
};
//原发器UserInfoDTO(用户信息类)
class UserInfoDTO
{
private:
string account;
string password;
string telNo;
public:
string getAccount() {
return account;
}
void setAccount(string account) {
this->account = account;
}
string getPassword() {
return password;
}
void setPassword(string password) {
this->password = password;
}
string getTelNo() {
return telNo;
}
void setTelNo(string telNo) {
this->telNo = telNo;
}
Memento* saveMemento()
{
return new Memento(account, password, telNo);
}
void restoreMemento(Memento* memento)
{
this->account = memento->getAccount();
this->password = memento->getPassword();
this->telNo = memento->getTelNo();
}
void show()
{
cout << "Account:" << this->account << endl << "Password:" << this->password << endl
<< "TelNo:" << this->telNo << endl;
}
};
//负责人Caretaker
class Caretaker {
public:
Caretaker() {}
Memento* getMemento() {
return memento.get();}
void setMemento(Memento *memento) {
this->memento.reset(memento);}
private:
shared_ptr<Memento> memento;
};
int main(int argc, char* argv[])
{
//创建原发器和负责人
UserInfoDTO user;
Caretaker c;
//定义初始状态
user.setAccount("zhasan");
user.setPassword("123");
user.setTelNo("1300");
cout << "状态一:" << endl;
user.show();
//保存状态
c.setMemento(user.saveMemento());
cout << "----------" << endl;
//更改状态
user.setPassword("111");
user.setTelNo("1311");
cout << "状态二:" << endl;
user.show();
cout << "----------" << endl;
//恢复状态
user.restoreMemento(c.getMemento());
cout << "回到状态一:" << endl;
user.show();
return 0;
}
关键点负责人Caractor保存需要保存的Memento数据,这样不管UserInfoDTO对象被销毁还是更改都可以还原状态。用起来还是可以的,不过又要增加一个负责人类的维护,不算方便