php 设计模式之 备忘录



1. 备忘录模式

在不破坏封装性的前提下,捕获一个对象的内部状态

在该对象之外保存这个状态,就可将该对象恢复到原先保存的状态


2. 实列

class Originator {
    private $state;
    public function SetMeneto(Memento $m) {
        $this->state = $m->GetState();
    }
    public function CreateMemento() {
        $m = new Memento();
        $m->SetState($this->state);
        return $m;
    }

    public function SetState($state) {
        $this->state = $state;
    }

    public function ShowState() {
        echo $this->state, PHP_EOL;
    }
}



class Memento {   // 存储的媒介
    private $state;
    public function SetState($state) {
        $this->state = $state;
    }
    public function GetState() {
        return $this->state;
    }
}


class Caretaker {
    private $memento;
    public function SetMemento($memento) {
        $this->memento = $memento;
    }
    public function GetMemento() {
        return $this->memento;
    }
}


$o = new Originator();
$o->SetState('状态1');   // 设置数据
$o->ShowState();

$c = new Caretaker();
$c->SetMemento($o->CreateMemento());   // 保存数据

$o->SetState('状态2');   // 修改数据
$o->ShowState();

$o->SetMeneto($c->GetMemento());   // 退回数据
$o->ShowState();
posted @ 2020-12-31 15:36  linsonga  阅读(56)  评论(0编辑  收藏  举报