大话设计模式第十八章--备忘录模式

<?php
class Originator {
    private $state;
    public function __set($param, $value) {
        if ($param == 'state') {
            $this->state = $value;
        }
    }
    public function __get($param) {
        if ($param == 'state') {
            return $this->state;
        }
    }
    public function create_memento() : Memento {
        return (new Memento($this->state));
    }
    public function set_memento(Memento $memento) {
        $this->state = $memento->state;
    }
    public function show() {
        echo "state:" . $this->state ."<br/>";
    }
}

class Memento {
    private $state;
    public function __construct(string $state) {
        $this->state = $state;
    }
    public function __get($param) {
        if ($param == 'state') {
            return $this->state;
        }
    }
}

class Caretaker {
    private $memento;
    public function __set($param, $value) {
        if ($param == 'memento') {
            $this->memento= $value;
        }
    }
    public function __get($param) {
        if ($param == 'memento') {
            return $this->memento;
        }
    }
}


//client CODE
$o = new Originator();
$o->state = 'ON';
$o->show();

$c = new Caretaker();
$c->memento = $o->create_memento();

$o->state = 'OFF';
$o->show();

$o->set_memento($c->memento);
$o->show();

 

备忘录模式:

  在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。

  使用备忘录模式可以把复杂的对象内部信息对其他的对象屏蔽起来。

posted @ 2015-09-02 21:00  wy0314  阅读(123)  评论(0)    收藏  举报