软件设计——备忘录模式之多次撤销C++
改进课堂上的“用户信息操作撤销”实例,使得系统可以实现多次撤销(可以使用HashMap、ArrayList等集合数据结构实现)。
类图:
代码:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
/*
struct State {
string account;
string password;
string telNo;
};
class Memento {
private:
State* state;
public:
Memento(State* pstate) :state(pstate) {}
State* getState() {
return state;
}
};
*/
//备忘录
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 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() {
Memento memento(account, password, telNo);
return memento;
}
void restoreMenmento(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;
}
};
//管理者
class Caretaker {
private:
vector<Memento>mementos;
public:
Memento getMemento(int i) {
return mementos.at(i);
}
void setMemento(Memento memento) {
mementos.push_back(memento);
}
};
int main() {
int index = -1;
UserInfoDTO user;
Caretaker taker;
user.setAccount("zhangsan");
user.setPassword("123456");
user.setTelNo("13000000000");
cout << "状态一:" << endl;
taker.setMemento(user.saveMemento());
index++;
user.show();
cout << "----------------------------------" << endl;
user.setPassword("111111");
user.setTelNo("13100001111");
cout << "状态二:" << endl;
taker.setMemento(user.saveMemento());
index++;
user.show();
cout << "----------------------------------" << endl;
user.setPassword("222222");
user.setTelNo("13100001111");
cout << "状态三:" << endl;
user.show();
cout << "----------------------------------" << endl;
cout << "回到状态二:" << endl;
index--;
user.restoreMenmento(taker.getMemento(1));
user.show();
cout << "----------------------------------" << endl;
cout << "回到状态一:" << endl;
index --;
user.restoreMenmento(taker.getMemento(0));
user.show();
cout << "----------------------------------" << endl;
}
运行结果: