[php]php设计模式 Memento (备忘录模式)

1 <?php
2 /**
3 * 备忘录模式
4 *
5 * 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可以将该对象恢复到保存的状态
6 */
7 class Memento
8 {
9 private$_state=null;
10
11 publicfunction __construct($state)
12 {
13 $this->_state =$state;
14 }
15
16 publicfunction getState()
17 {
18 return$this->_state;
19 }
20 }
21
22 class Caretaker
23 {
24 private$_memento=null;
25
26 publicfunction getMemento()
27 {
28 return$this->_memento;
29 }
30
31 publicfunction setMemento($memento)
32 {
33 $this->_memento =$memento;
34 }
35 }
36
37 class Originator
38 {
39 private$_state=null;
40
41 publicfunction getState()
42 {
43 return$this->_state;
44 }
45
46 publicfunction setState($state)
47 {
48 $this->_state =$state;
49 }
50
51 publicfunction createMemento()
52 {
53 returnnew Memento($this->_state);
54 }
55
56 publicfunction setMemento($memento)
57 {
58 $this->_state =$memento->getState();
59 }
60
61 publicfunction display()
62 {
63 echo"state = ".$this->_state."<br/>";
64 }
65 }
66
67 $objOriginator=new Originator();
68 $objOriginator->setState(0);
69 $objOriginator->display();
70
71 $objCareTaker=new CareTaker();
72 $objCareTaker->setMemento($objOriginator->createMemento());
73
74 $objOriginator->setState(1);
75 $objOriginator->display();
76
77 $objOriginator->setMemento($objCareTaker->getMemento());
78 $objOriginator->display();
原文地址:https://www.cnblogs.com/bluefrog/p/2090959.html