php备忘录模式(memento pattern)

晚上刷起来。

<?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();

?>

猜你喜欢

转载自www.cnblogs.com/aguncn/p/11185431.html
0条评论
添加一条新回复