Memento is a behavioral design pattern that allows making snapshots of an object’s state and restoring it in future.

The Memento doesn’t compromise the internal structure of the object it works with, as well as data kept inside the snapshots.

#include <iostream>
#include <string>
#include <vector>
using namespace std;


class Memento {
public:
	Memento(string text):text{text} {}
	string text;
};

class Metin {
	string current_text;
public:
	string get_text() {
		return current_text;
	}
	void set_state(Memento& mem) {
		current_text = mem.text;
	}
	Memento save() {
		return Memento(current_text);
	}
	void add_text(string text) {
		current_text += text;
	}
};

class YaziEditor {
	vector<Memento> undo_history; 

	Metin metin; 
public:
	void add_text(string text) {
		metin.add_text(text);
	}
	void undo() {
		if (!undo_history.empty()) {
			metin.set_state(undo_history[undo_history.size() - 1]);
			undo_history.pop_back();
		}

	}
	void save() {
		undo_history.push_back(metin.save());
	}
	void get_text() {
		cout << metin.get_text() << endl;;
	}

};

int main() {
	YaziEditor yazbel; 

	yazbel.add_text("Merhaba ");
	yazbel.get_text();
	yazbel.save();

	yazbel.add_text("Dunya\n");
	yazbel.get_text();
	yazbel.save();

	yazbel.add_text("Gamzedeyim deva bulmam garibim bir yuva kurmam\n");
	yazbel.get_text();
	yazbel.save();


	yazbel.undo();
	yazbel.get_text();
	yazbel.undo();
	yazbel.get_text();
	yazbel.undo();
	yazbel.get_text();

}
Merhaba
Merhaba Dunya

Merhaba Dunya
Gamzedeyim deva bulmam garibim bir yuva kurmam

Merhaba Dunya
Gamzedeyim deva bulmam garibim bir yuva kurmam

Merhaba Dunya

Merhaba

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *