-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemento.php
More file actions
75 lines (62 loc) · 1.66 KB
/
Memento.php
File metadata and controls
75 lines (62 loc) · 1.66 KB
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
<?php
//保存一个对象的某个状态,以便在适当的时候恢复对象
//使用场景: 1、需要保存/恢复数据的相关状态场景。 2、提供一个可回滚的操作。
class Memento
{
private $state;
public function __construct(string $state)
{
$this->state = $state;
}
public function getState()
{
return $this->state;
}
}
class Originator
{
private $state;
public function setState(string $state)
{
$this->state = $state;
}
public function getState()
{
echo $this->state."\n";
}
public function saveStateToMemento()
{
return new Memento($this->state);
}
public function restoreFromMemento(Memento $memento)
{
return $memento->getState();
}
}
class CareTaker
{
private $list = [];
public function add(Memento $memento)
{
$this->list[] = $memento;
}
public function get($index)
{
return $this->list[$index];
}
}
$origin = new Originator();
$caretaker = new CareTaker();
$origin->setState('hello origig #1');
$origin->setState('hello origin #2');
$origin->getState();
$memento1 = $origin->saveStateToMemento();
$caretaker->add($memento1);
$origin->setState('hello origin #3');
$memento2 = $origin->saveStateToMemento();
$caretaker->add($memento2);
$origin->getState();
$memento4 = $caretaker->get(1);
$origin->restoreFromMemento($memento4);
$origin->getState();
?>