-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathState.php
More file actions
83 lines (73 loc) · 1.92 KB
/
State.php
File metadata and controls
83 lines (73 loc) · 1.92 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
76
77
78
79
80
81
82
83
<?php
/*
*状态模式
*
*现实生活示例
*想象一下,你正在使用一些绘图应用程序,你可以选择笔刷来绘画,刷子根据所选颜色改变其行为,
*即如果选择红色,它将绘制为红色,如果选择蓝色,那么它将绘制蓝色等。
*
*概述
*当状态改变时,类的行为也发生改变。
*
*维基百科
*状态模式是以面向对象的方式实现状态机的行为设计模式。对于状态模式,
*通过将每个单独状态实现为派生类的状态模式接口, 来实现一个状态机,
*并通过调用模式超类的方法来实现状态转换。状态模式可以被解释为一种策略模式,
*它能够通过调用模式接口定义的方法来切换当前策略。
*
*/
//程序示例
//以文本编辑器为例,编辑器可以改变文本的状态如选中粗体,就会以粗体输入文本,
//选中斜体便以斜体输入。
//首先是状态接口和一些状态实现
interface WritingState
{
public function write(string $words);
}
class UpperCase implements WritingState
{
public function write(string $words)
{
echo strtoupper($words) . PHP_EOL;
}
}
class LowerCase implements WritingState
{
public function write(string $words)
{
echo strtolower($words) . PHP_EOL;
}
}
class Defaults implements WritingState
{
public function write(string $words)
{
echo $words . PHP_EOL;
}
}
//然后是文本编辑器
class TextEditor
{
protected $state;
public function __construct(WritingState $state)
{
$this->state = $state;
}
public function setState(WritingState $state)
{
$this->state = $state;
}
public function type(string $words)
{
$this->state->write($words);
}
}
//使用
$editor = new TextEditor(new Defaults());
$editor->type('First line');
$editor->setState(new UpperCase());
$editor->type('Second line');
$editor->type('Third line');
$editor->setState(new LowerCase());
$editor->type('Fourth line');
$editor->type('Fifth line');