喜迎
春节

设计模式——解释器模式


说明

示例

下面看下解释器模式的代码实现

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
interface Expression{
public function interpret(Context $context): int;
}

class Plus implements Expression{
public function interpret(Context $context): int{
return $context->getNum1() + $context->getNum2();
}
}

class Minus implements Expression{
public function interpret(Context $context): int{
return $context->getNum1() - $context->getNum2();
}
}

class Context{
private int $num1,$num2;

public function __construct(int $num1,int $num2){
$this->num1 = $num1;
$this->num2 = $num2;
}

public function getNum1(): int{
return $this->num1;
}

public function setNum1(int $num1){
$this->num1 = $num1;
}

public function getNum2(): int{
return $this->num2;
}

public function setNum2(int $num2){
$this->num2 = $num2;
}
}


// 调用
$result = (new Minus())->interpret(new Context((new Plus())->interpret(new Context(9,2)),8));
echo $result;
// output: 3

总结


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