违反捕获使具体化恢复这种模式在不破坏封装性的前提下捕获和具体化对象的内部状态以便对象可以恢复最后的状态
Caretaker(看管者)
This class is responsible for the memento's safekeeping while never operating on or examining(检查) the contents of a memento.
(这个类是负责备忘录的保护,而从来没有操作或检查备忘录的内容。)
Memento(备忘录)
This class stores internal state of the Originator(起源) object and protects against(反对) access by objects other than the originator.
(这类存储发起人对象的内部状态和防止除了发起人之外的对象访问。)
Originator(起源)
This class creates a memento containing a snapshot(快照) of its current internal state and uses the memento to restore its internal state.
(这个类创建包含其当前的内部状态的一个快照的一个备忘录和使用备忘录来恢复它的内部状态。)
<?php
class Caretaker
{
private $_memento = null;
public function getMemento() {
return $this->_memento;
}
public function setMemento($memento) {
$this->_memento = $memento;
}
}
class Memento
{
private $_state = null;
public function __construct($state) {
$this->_state = $state;
}
public function getState() {
return $this->_state;
}
}
class Originator
{
private $_state = null;
public function getState() {
return $this->_state;
}
public function setState($state) {
$this->_state = $state;
}
public function createMemento() {
return new Memento($this->_state);
}
public function setMemento($memento) {
$this->_state = $memento->getState();
}
public function display() {
echo "state = " . $this->_state . "";
}
}
$objOriginator = new Originator();
$objOriginator->setState(0);
$objOriginator->display();
$objCareTaker = new CareTaker();
$objCareTaker->setMemento($objOriginator->createMemento());
$objOriginator->setState(1);
$objOriginator->display();
$objOriginator->setMemento($objCareTaker->getMemento());
$objOriginator->display();
评论