DEV Community

Cover image for memento pattern
Simone Gentili
Simone Gentili

Posted on

memento pattern

Elements

Is is composed by two elements. First one is an originator. Second one is memento. It separate object state from object manipulation. Memento class store the status. Originator class manipulate the status.

Memento class

Code speak itself. This class read a content and provide same content. The content is the status of the book (libro in italian).

class LibroMemento
{
    public function __construct(private string $content)
    {

    }

    public function getContent()
    {
        return $this->content;
    }
}
Enter fullscreen mode Exit fullscreen mode

Originator class

In this case the originator class add paragraph to the book content. It contains two special methods: save and restore. Save generate a memento object. It contains the content of the book and create a memento instance with that content. Then with restore, get the content from a memento and become that object.

class Libro
{
    public function __construct(private string $content = '') {}
    public function addParagrafo(string $paragrafo)
    {
        $this->content .= "\n" . $paragrafo;
    }

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

    public function restore(LibroMemento $libro)
    {
        $this->content = $libro->getContent();
    }

    public function __toString()
    {
        return $this->content;
    }
}
Enter fullscreen mode Exit fullscreen mode

Usage

In this first case, echo returns

Ciao sono Simone
Sono un programmatore

$libro = new Libro;
$libro->addParagrafo('Ciao sono Simone');
$savepoint = $libro->save();
$libro->addParagrafo('Sono un programmatore');
echo $libro;
Enter fullscreen mode Exit fullscreen mode

In this first case, echo returns

Ciao sono Simone

Because $savepoint contains only first paragraph.

$libro->restore($savepoint);
echo $libro;
Enter fullscreen mode Exit fullscreen mode

Conclusion

This pattern is commonly used in software of video, image, text editors and games. It separate the logic of updates from the status itself.

Top comments (0)