设计模式C++实现(15)——备忘录模式

本文通过一个C++实例展示了备忘录模式的运用,该模式允许在不暴露对象内部状态的情况下保存和恢复对象的状态。在示例中,创建了原发器`UserInfoDTO`和负责人`Caretaker`类,前者用于保存用户信息并提供状态的保存和恢复,后者负责存储备忘录对象。这种设计模式在需要记录和回滚对象状态变化的场景下非常有用,但可能会增加额外的类维护成本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定义:在不暴露对象实现细节的情况下保存和恢复对象之前的状态。

#include <iostream>
#include <string>

using namespace std;


//备忘录Memento
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;
	}
};


//原发器UserInfoDTO(用户信息类)
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 << "Password:" << this->password << endl
			<< "TelNo:" << this->telNo << endl;
	}
};

//负责人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(int argc, char* argv[])
{
	//创建原发器和负责人 
	UserInfoDTO user;
	Caretaker c;

	//定义初始状态 
	user.setAccount("zhasan");
	user.setPassword("123");
	user.setTelNo("1300");

	cout << "状态一:" << endl;
	user.show();

	//保存状态 
	c.setMemento(user.saveMemento());
	cout << "----------" << endl;

	//更改状态 
	user.setPassword("111");
	user.setTelNo("1311");
	cout << "状态二:" << endl;
	user.show();
	cout << "----------" << endl;

	//恢复状态 
	user.restoreMemento(c.getMemento());
	cout << "回到状态一:" << endl;
	user.show();
	return 0;
}

在这里插入图片描述

 关键点负责人Caractor保存需要保存的Memento数据,这样不管UserInfoDTO对象被销毁还是更改都可以还原状态。用起来还是可以的,不过又要增加一个负责人类的维护,不算方便

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值