<?php
// 备忘录类
class Memento
{
private $state;
public function __construct(string $state)
{
$this->state = $state;
}
public function getState(): string
{
return $this->state;
}
}
// 发起人类
class Originator
{
private $state;
public function setState(string $state): void
{
echo "发起人: 设置状态为 $state\n";
$this->state = $state;
}
public function saveStateToMemento(): Memento
{
echo "发起人: 保存状态到备忘录\n";
return new Memento($this->state);
}
public function getStateFromMemento(Memento $memento): void
{
$this->state = $memento->getState();
echo "发起人: 从备忘录恢复状态为 $this->state\n";
}
}
// 看护者类
class Caretaker
{
private $mementoList = [];
public function add(Memento $state): void
{
$this->mementoList[] = $state;
}
public function get(int $index): Memento
{
return $this->mementoList[$index];
}
}
// 客户端代码
$originator = new Originator();
$caretaker = new Caretaker();
$originator->setState("状态1");
$originator->setState("状态2");
$caretaker->add($originator->saveStateToMemento());
$originator->setState("状态3");
$caretaker->add($originator->saveStateToMemento());
$originator->setState("状态4");
echo "\n当前状态: " . $originator->saveStateToMemento()->getState() . "\n";
$originator->getStateFromMemento($caretaker->get(0));
echo "\n恢复到第一个保存的状态: " . $originator->saveStateToMemento()->getState() . "\n";
$originator->getStateFromMemento($caretaker->get(1));
echo "\n恢复到第二个保存的状态: " . $originator->saveStateToMemento()->getState() . "\n";