喜迎
春节

设计模式——状态模式


说明

示例

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

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 !
评 论
 上一篇
设计模式——桥接模式
设计模式——桥接模式
说明 桥接模式就是把事物和其具体实现分开,使他们可以各自独立的变化。桥接的用意是:将抽象化与实现化解耦,使得二者可以独立变化,像我们常用的JDBC桥DriverManager一样,JDBC进行连接数据库的时候,在各个数据库之间进行切换,基
2022-05-19
下一篇 
设计模式——策略模式
设计模式——策略模式
说明示例下面看下策略模式的代码实现 12345678910111213141516171819202122232425262728293031323334353637383940interface ICalculator{ publi
2022-05-19
  目录
hexo