<?php
declare(strict_types=1);
// 记忆模式是关于捕获和存储对象的当前状态的方式,以便以后可以平滑地恢复它。
// php 技术群:781742505
/**
* Class EditorMemento
*/
class EditorMemento
{
/**
* @var string
*/
protected $content;
/**
* EditorMemento constructor.
*
* @param string $content
*/
public function __construct(string $content)
{
$this->content = $content;
}
/**
* @return string
*/
public function getContent()
{
return $this->content;
}
}
/**
* Class Editor
*/
class Editor
{
/**
* @var string
*/
protected $content = '';
/**
* @param string $words
*/
public function type(string $words)
{
$this->content = $this->content.' '.$words;
}
/**
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* @return EditorMemento
*/
public function save()
{
return new EditorMemento($this->content);
}
/**
* @param EditorMemento $memento
*/
public function restore(EditorMemento $memento)
{
$this->content = $memento->getContent();
}
}
$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()
."\n"; // This is the first sentence. This is second. And this is third.
// Restoring to last saved state
$editor->restore($saved);
echo $editor->getContent(); // This is the first sentence. This is second.
备忘录模式
最新推荐文章于 2024-03-02 19:52:32 发布