通过改变类的状态来实现对它行为的切换。

看代码还是比较好理解的:

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
abstract class State
{
protected string $state;

public function getState(): string
{
return $this->state;
}

abstract public function handle();
}

class StateContext
{
protected State $state;


public function setState(State $state)
{
$this->state = $state;
}

public function getState(): string
{
return $this->state->getState();
}

public function handle()
{
$this->state->handle();
}
}

class CreateOrder extends State
{
public function __construct()
{
$this->state = 'create';
}

public function handle()
{
echo '创建订单', PHP_EOL;
}
}

class FinishOrder extends State
{

public function __construct()
{
$this->state = 'finish';
}


public function handle()
{
echo '结束订单', PHP_EOL;
}
}

$stateContext = new StateContext();
$stateContext->setState(new CreateOrder());
$stateContext->handle();
echo $stateContext->getState(), PHP_EOL;

$stateContext->setState(new FinishOrder());
$stateContext->handle();
echo $stateContext->getState(), PHP_EOL;

将状态独立,然后在外部控制状态切换,已实现对其行为控制。