在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可将对象恢复到原先保存的状态<br />就是备份,存档,将对象某一时刻备份下来,然后需要的话,还原,管理类可以存储多个备份<br />git svn 备份,都是备忘录模式的体现<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/22438777/1635488280324-add4072f-75f2-409c-88d4-11deb49ecf6e.png#clientId=u95146fba-8085-4&from=paste&height=351&id=u0619119a&margin=%5Bobject%20Object%5D&name=image.png&originHeight=351&originWidth=752&originalType=binary&ratio=1&size=46277&status=done&style=none&taskId=u7244f310-e990-4bad-a73e-520bb815bba&width=752)
<?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();