Skip to main content

Real World Example

Take the example of calculator (i.e. originator), where whenever you perform some calculation the last calculation is saved in memory (i.e. memento) so that you can get back to it and maybe get it restored using some action buttons (i.e. caretaker).

In Plain Words

Memento pattern is about capturing and storing the current state of an object in a manner that it can be restored later on in a smooth manner.

Wikipedia Says

The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).
Usually useful when you need to provide some sort of undo functionality.

Programmatic Example

Lets take an example of text editor which keeps saving the state from time to time and that you can restore if you want. First of all we have our memento object that will be able to hold the editor state:
class EditorMemento
{
    protected $content;

    public function __construct(string $content)
    {
        $this->content = $content;
    }

    public function getContent()
    {
        return $this->content;
    }
}
Then we have our editor i.e. originator that is going to use memento object:
class Editor
{
    protected $content = '';

    public function type(string $words)
    {
        $this->content = $this->content . ' ' . $words;
    }

    public function getContent()
    {
        return $this->content;
    }

    public function save()
    {
        return new EditorMemento($this->content);
    }

    public function restore(EditorMemento $memento)
    {
        $this->content = $memento->getContent();
    }
}
And then it can be used as:
$editor = new Editor();

// Type some stuff
$editor->type('This is the first sentence.');
$editor->type('This is second.');

// Save the state to restore to : This is the first sentence. This is second.
$saved = $editor->save();

// Type some more
$editor->type('And this is third.');

// Output: Content before Saving
echo $editor->getContent(); // This is the first sentence. This is second. And this is third.

// Restoring to last saved state
$editor->restore($saved);

$editor->getContent(); // This is the first sentence. This is second.

Key Points

  • Preserves encapsulation boundaries - the memento object stores state without exposing internal structure
  • Simplifies the originator by offloading state management to memento objects
  • Useful for implementing undo/redo functionality
  • Can be memory-intensive if states are saved frequently
The memento pattern is particularly useful in applications that require undo/redo functionality, such as text editors, graphic editors, or any application where you need to track state changes.

Build docs developers (and LLMs) love