概念: 在不违反封装性的前提下,捕获一个对象的内部状态,并在需要时恢复对象的状态
class Memento {
private $state;
public function __construct($state) {
$this->state = $state;
}
public function getState() {
return $this->state;
}
}
class Originator {
private $state;
public function setState($state) {
$this->state = $state;
}
public function save() {
return new Memento($this->state);
}
public function restore(Memento $memento) {
$this->state = $memento->getState();
}
}
// 使用
$originator = new Originator();
$originator->setState("State1");
$memento = $originator->save();
$originator->setState("State2");
$originator->restore($memento); // 恢复为 State1