喜迎
春节

设计模式——状态模式


说明

示例

下面看下状态模式的代码实现

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
class State{
private string $value;

public function getValue(): string{
return $this->value;
}

public function setValue(string $value){
$this->value = $value;
}

public function method1(){
echo "execute the first opt!" . PHP_EOL;
}

public function method2(){
echo "execute the second opt!" . PHP_EOL;
}
}

class Context{
private State $state;

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

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

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

public function method(){
if ($this->state->getValue() == 'state1'){
$this->state->method1();;
}else if($this->state->getValue() == 'state2'){
$this->state->method2();
}
}
}


// 调用
$state = new State();
$context = new Context($state);

$state->setValue('state1');
$context->method();

$state->setValue('state2');
$context->method();
/**
* output:
* execute the first opt!
* execute the second opt!
*
*/


总结


文章作者: Crazy Boy
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Crazy Boy !
评 论
  目录
hexo