Memento stores a previous state or value so that it can be restored at a later time.
The memento pattern is a software design pattern that provides the ability |
to restore an object to its previous state (undo via rollback). |
The memento pattern is used by two objects: the originator and a caretaker. The |
originator is some object that has an internal state. The caretaker is going to |
do something to the originator, but wants to be able to undo the change. |
The |
caretaker first asks the originator for a memento object. Then it does whatever |
operation (or sequence of operations) it was going to do. To roll back to the |
state before the operations, it returns the memento object to the originator. |
#include <iostream>
#include <string>
class Memento
{
std::string oldString;
public:
Memento(std::string & str, const std::string newString) : oldString(str)
{
str = newString;
}
void undo(std::string & str)
{
str = oldString;
}
};
void hello_world(Memento & memento)
{
std::string message;
memento.undo(message);
std::cout << message << std::endl;
}
int main()
{
std::string hw("Hello world!");
Memento mem(hw, "Goodbye, cruel world!");
hello_world(mem);
return 0;
}