设计模式:备忘录模式-实现编辑器多级撤销

Editor:存储内容、生成EditorState


#pragma once
#include <string>
#include "EditorState.h"
using namespace std;
class Editor
{
public:
	EditorState* createState();
	void restore(EditorState& state);
	void setContent(string str);
	string getContent();
private:
	string content;
};


#include "Editor.h"
#include <iostream>
using namespace std;
EditorState* Editor::createState()
{
	return new EditorState(content);
}

void Editor::restore(EditorState& state)
{
	content = state.getContent();
	delete &state;
}

void Editor::setContent(string str)
{
	
	content = str;
}

string Editor::getContent()
{

	return content;
}

EditorState:存储内容

#pragma once
#include <string>
using namespace std;
class EditorState
{
public:
	EditorState(string& content);
	string& getContent();
private:
	string content;
};


#include "EditorState.h"

EditorState::EditorState(string& content) : content{content}
{
}

string& EditorState::getContent()
{
	return content;
}

History:保存、操作历史状态

#pragma once
#include <string>
#include <vector>
#include "EditorState.h"
using namespace std;
class History
{
private:
	vector<EditorState*> states;
public:
	void push(EditorState* state);
	EditorState* pop();
};


#include "History.h"

void History::push(EditorState* state)
{
	states.push_back(state);
}

EditorState* History::pop()
{
	EditorState* state = states.back();
	states.pop_back();
	return state;
	
}

Main function:

#include <iostream>
#include "Editor.h"
#include "History.h"
using namespace std;

void setContent(string str, Editor& editor, History& history) {
    history.push(editor.createState());
    editor.setContent(str);
    cout << "writeContent:" << editor.getContent() << endl;
    
}

void undo(Editor& editor, History& history) {
    EditorState* state = history.pop();
    editor.restore(*state);
    cout << "undoContent:" << editor.getContent() << endl;
}

int main()
{
    Editor editor;
    History history;
    setContent("1", editor, history);
    setContent("2", editor, history);
    setContent("3", editor, history);
    undo(editor, history);
    undo(editor, history);
    undo(editor, history);
}

输出结果:

writeContent:1
writeContent:2
writeContent:3
undoContent:2
undoContent:1
undoContent:
 

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值