设计模式-备忘录模式(c++)


用户信息操作撤销实例,使得系统可以实现多次撤销(可以使用HashMapArrayList等集合数据结构实现)。

#include
#include
#include
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 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<password<telNo<setAccount("zhangsan");
	user->setPassword("123456");
	user->setTelNo("13000000000");
	cout<<"状态一:"<show();
	c->setMemento(user->saveMemento());//保存备忘录
	cout<<"---------------------------"<setPassword("111111");
	user->setTelNo("13100001111");
	cout<<"状态二:"<show();
	c->setMemento(user->saveMemento());//保存备忘录
	cout<<"---------------------------"<setPassword("1ewe");
	user->setTelNo("13123251331");
	cout<<"状态三:"<show();
	c->setMemento(user->saveMemento());//保存备忘录
	cout<<"---------------------------"<restoreMemento(c->getMemento());//已经是状态三,不需要恢复,因此丢掉
	user->restoreMemento(c->getMemento());//从备忘录中恢复
	cout<<"回到状态二:"<show();
	cout<<"---------------------------"<restoreMemento(c->getMemento());//从备忘录中恢复
	cout<<"回到状态一:"<show();
	cout<<"---------------------------"<
						  
					  

相关