Статья
Шаблон проектирования "Снимок"

Шаблон проектирования "Снимок"

14 апреля 2020

Относится к поведенческим шаблонам.

Позволяет сохранить состояние объекта, чтобы впоследствии восстановить его в это состояние.

Плюсы:
-  позволяет сохранить состояние объекта, не нарушая при этом инкапсуляцию


Пример на PHP

Создадим класс-хранитель Memento и класс Editor:

class Memento
{
    protected $content;

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

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

class Editor
{
    protected $content = '';

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

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

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

    public function restore(Memento $memento)
    {
        $this->content = $memento->getContent();
    }
}


Использование:

$editor = new Editor();
$editor->setContent('First state.');
$savedState = $editor->save();

$editor->setContent('Second state.');
echo $editor->getContent(); // Second state.

$editor->restore($savedState);
$editor->getContent(); // First state.


Пример на Go

package main

type Memento struct {
   content string
}

func (m *Memento) GetContent() string {
   return m.content
}

type Editor struct {
   content string
}

func (e *Editor) SetContent(content string) {
   e.content = content
}

func (e *Editor) GetContent() string {
   return e.content
}

func (e *Editor) Save() *Memento {
   return &Memento{
      content: e.content,
   }
}

func (e *Editor) Restore(memento *Memento)  {
   e.content = memento.GetContent()
}

func main() {
   editor := Editor{}
   editor.SetContent("First state.")
   
   state := editor.Save()
   editor.SetContent("Second state.")
   editor.GetContent() // Second state.
   
   editor.Restore(state)
   editor.GetContent() // First state.
}



Источники:
http://designpatternsphp.readthedocs.io/ru/latest/Behavioral/Memento/README.html
https://habrahabr.ru/company/mailru/blog/325492/