设计模式-备忘录模式(c++)
“用户信息操作撤销”实例,使得系统可以实现多次撤销(可以使用HashMap、ArrayList等集合数据结构实现)。
#include<iostream>
#include<string>
#include<list>
using namespace std;
//备忘录
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;
}
};
//负责人
class Caretaker {
private: Memento *memento;
list<Memento*> mens;
public: Memento *getMemento()
{
memento = mens.back();
mens.pop_back();
return memento;
}
void setMemento(Memento *memento)
{
this->memento = memento;
mens.push_back(memento);
}
};
//用户信息
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;
cout<<"Password:" << this->password<<endl;
cout<<"TelNo:" <<this->telNo<<endl;
}
};
int main(){
UserInfoDTO *user = new UserInfoDTO();
Caretaker *c = new Caretaker();
user->setAccount("zhangsan");
user->setPassword("123456");
user->setTelNo("13000000000");
cout<<"状态一:"<<endl;
user->show();
c->setMemento(user->saveMemento());//保存备忘录
cout<<"---------------------------"<<endl;
user->setPassword("111111");
user->setTelNo("13100001111");
cout<<"状态二:"<<endl;
user->show();
c->setMemento(user->saveMemento());//保存备忘录
cout<<"---------------------------"<<endl;
user->setPassword("1ewe");
user->setTelNo("13123251331");
cout<<"状态三:"<<endl;
user->show();
c->setMemento(user->saveMemento());//保存备忘录
cout<<"---------------------------"<<endl;
// user.restoreMemento(c.getMemento());//从备忘录中恢复
// System.out.println("回到状态三:");
// user.show();
// System.out.println("---------------------------");
user->restoreMemento(c->getMemento());//已经是状态三,不需要恢复,因此丢掉
user->restoreMemento(c->getMemento());//从备忘录中恢复
cout<<"回到状态二:"<<endl;
user->show();
cout<<"---------------------------"<<endl;
user->restoreMemento(c->getMemento());//从备忘录中恢复
cout<<"回到状态一:"<<endl;
user->show();
cout<<"---------------------------"<<endl;
}


浙公网安备 33010602011771号