1. 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可将对象恢复到原先保存的状态<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)
    1. <?php
    2. //一个正常的类
    3. class Originator
    4. {
    5. private $state;
    6. //备份还原
    7. public function SetMeneto(Memento $m)
    8. {
    9. $this->state = $m->GetState();
    10. }
    11. //创建备份
    12. public function CreateMemento()
    13. {
    14. $m = new Memento();
    15. $m->SetState($this->state);
    16. return $m;
    17. }
    18. public function SetState($state)
    19. {
    20. $this->state = $state;
    21. }
    22. public function ShowState()
    23. {
    24. echo $this->state, PHP_EOL;
    25. }
    26. }
    27. //备忘录类
    28. class Memento
    29. {
    30. private $state;
    31. public function SetState($state)
    32. {
    33. $this->state = $state;
    34. }
    35. public function GetState()
    36. {
    37. return $this->state;
    38. }
    39. }
    40. //管理类
    41. class Caretaker
    42. {
    43. private $memento;
    44. public function SetMemento($memento)
    45. {
    46. $this->memento = $memento;
    47. }
    48. public function GetMemento()
    49. {
    50. return $this->memento;
    51. }
    52. }
    53. $o = new Originator();
    54. $o->SetState('状态1');
    55. $o->ShowState();
    56. // 保存状态
    57. $c = new Caretaker();
    58. $c->SetMemento($o->CreateMemento());
    59. $o->SetState('状态2');
    60. $o->ShowState();
    61. // 还原状态
    62. $o->SetMeneto($c->GetMemento());
    63. $o->ShowState();