设计模式之备忘录模式实例(c++)
·
备忘录模式
在不破坏封装的前提下,捕获一个对象的内部装,并在该对象之外保存这个状态,这样可以在以后将对象恢复到原先保存的状态。
备忘录模式一般包含Originator(原发器)、Memento(备忘录)、Caretaker(负责人)。负责人用来管理备忘录。
备忘录模式实例之用户信息操作撤销

从类图可知UserInfoDTO依赖注入Memento来进行创建备份,交给Caretaker管理(聚合)Memento备忘录。
下面是c++版本的实现。
备忘录Memento
//备忘录Memento
class Memento{
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;
}
private:
string account;
string password;
string telNo;
};
原发器UserInfoDTO(用户信息类)
//原发器UserInfoDTO(用户信息类)
class UserInfoDTO{
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;
}
private:
string account;
string password;
string telNo;
};
负责人Caretaker
//负责人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(void){
//创建原发器和负责人
UserInfoDTO user;
Caretaker c;
//定义初始状态
user.setAccount("zhangsan");
user.setPassword("123456");
user.setTelNo("130000000");
cout << "状态一:" << endl;
user.show();
//保存状态
c.setMemento(user.saveMemento());
cout << "----------" << endl;
//更改状态
user.setPassword("11111");
user.setTelNo("131111110");
cout << "状态二:" << endl;
user.show();
cout << "----------" << endl;
//恢复状态
user.restoreMemento(c.getMemento());
cout << "回到状态一:" << endl;
user.show();
return 0;
}
输出结果

更多推荐
所有评论(0)