晚上刷起来。

<?php
/*
The memento pattern provides the object restore functionality. Implementation is
done through three different objects; originator, caretaker, and a memento, where
the originator is the one preserving the internal state required for a later restore.
*/

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) {
        return $this->state = $state;
    }

    public function getState() {
        return $this->state;
    }

    public function saveToMemento() {
        return new Memento($this->state);
    }

    public function restoreFromMemento(Memento $memento) {
        $this->state = $memento->getState();
    }
}

$saveStates = array();

$originator = new Originator();
$originator->setState('new');
$originator->setState('pending');
$saveStates[] = $originator->saveToMemento();
$originator->setState('processing');
$saveStates[] = $originator->saveToMemento();
$originator->setState('complete');
$originator->restoreFromMemento($saveStates[1]);

echo $originator->getState();

?>

php备忘录模式(memento pattern)-LMLPHP

04-14 07:28