喜迎
春节

设计模式——状态模式


说明

示例

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

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 !
评 论
 上一篇
设计模式——策略模式
设计模式——策略模式
说明示例下面看下策略模式的代码实现 12345678910111213141516171819202122232425262728293031323334353637383940interface ICalculator{ publi
2022-05-19
下一篇 
设计模式——简单工厂方法模式
设计模式——简单工厂方法模式
说明凡是出现了大量的产品需要创建,并且具有共同的接口时,可以通过工厂方法模式进行创建。就是建立一个工厂类,对实现了同一接口的一些类进行实例的创建。首先看下关系图: 示例下面讲解下静态工厂方法模式的代码实现 创建公共接口123interfa
2022-05-19
  目录
hexo