-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMemento.php
136 lines (106 loc) · 2.18 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<?php
/**
* This pattern solves the problem to save an objectstate without to show concrtete implementation to the saving layer
* a usage could be a siple implementation of a undo function
*/
/**
* Class Originator
*/
class Originator
{
/**
* @var string
*/
private $state = '';
/**
* @return string
*/
public function getState()
{
return $this->state;
}
/**
* @param string $state
*/
public function setState($state)
{
$this->state = $state;
}
/**
* @return Memento
*/
public function createMemento()
{
return new Memento($this->state);
}
/**
* @param Memento $memento
*/
public function setMemento(Memento $memento)
{
$this->state = $memento->getState();
}
}
/**
* Class Memento
*/
class Memento
{
/**
* @var string
*/
public $state = '';
/**
* @param String $state
*/
public function __construct(String $state)
{
$this->state = $state;
}
/**
* @return string
*/
public function getState()
{
return $this->state;
}
}
/**
* Class CareTaker
*/
class CareTaker
{
/**
* @var Memento[]
*/
public $mementos = array();
/**
* @param Memento $memento
*/
public function addMemento(Memento $memento)
{
array_push($this->mementos, $memento);
}
/**
* @return mixed
*/
public function getLastMemento()
{
$lastResult = array_pop($this->mementos);
$end = count($this->mementos);
unset($this->mementos[$end]);
return $lastResult;
}
}
$careTaker = new CareTaker();
$originator = new Originator();
$originator->setState('a first state');
$careTaker->addMemento($originator->createMemento());
$originator->setState('a second state');
$careTaker->addMemento($originator->createMemento());
$originator->setState('a third state');
echo PHP_EOL . $originator->getState();
$originator->setMemento($careTaker->getLastMemento());
echo PHP_EOL . $originator->getState();
$originator->setMemento($careTaker->getLastMemento());
echo PHP_EOL . $originator->getState();