-
Notifications
You must be signed in to change notification settings - Fork 2
/
State.php
85 lines (69 loc) · 1.49 KB
/
State.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
<?php
namespace DesignPatterns\Behavioral;
/**
* Editor contains a reference to an instance of a State interface,
* which represents the current editor state (e.g. upper case, lower case or default)
*/
class TextEditor
{
protected $state;
public function __construct(State $state)
{
$this->state = $state;
}
/**
* Allows changing the editor state at runtime
* @param State $state
*/
public function setState(State $state)
{
$this->state = $state;
}
/**
* Just printing words based on current state
* @param string $words
*/
public function type(string $words)
{
$this->state->write($words);
}
}
/**
* State interface declares methods that all Concrete State should implement
*/
interface State
{
public function write(string $words);
}
class DefaultState implements State
{
public function write(string $words)
{
echo $words . PHP_EOL;
}
}
class UpperCase implements State
{
public function write(string $words)
{
echo strtoupper($words) . PHP_EOL;
}
}
class LowerCase implements State
{
public function write(string $words)
{
echo strtolower($words) . PHP_EOL;
}
}
# Client code example
$editor = new TextEditor(new DefaultState());
$editor->type('First line');
$editor->setState(new UpperCase());
$editor->type('Second line');
$editor->setState(new LowerCase());
$editor->type('Third line');
/* Output:
First line
SECOND LINE
third line */