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