在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可将对象恢复到原先保存的状态<br />就是备份,存档,将对象某一时刻备份下来,然后需要的话,还原,管理类可以存储多个备份<br />git svn 备份,都是备忘录模式的体现<br />
<?php
//一个正常的类
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();