每日博客

备忘录模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解备忘录模式的动机,掌握该模式的结构;

2、能够利用备忘录模式解决实际问题。

 

 

[实验任务一]:多次撤销

改进课堂上的“用户信息操作撤销”实例,使得系统可以实现多次撤销(可以使用HashMap、ArrayList等集合数据结构实现)。

C++版

#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());
user->restoreMemento(c->getMemento());
cout << "回到状态二:" << endl;
user->show();
cout << "---------------------------" << endl;
user->restoreMemento(c->getMemento());
cout << "回到状态一:" << endl;
user->show();
cout << "---------------------------" << endl;
return 0;
}

posted @ 2021-11-03 19:01  谦寻  阅读(49)  评论(0编辑  收藏  举报