加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php解释器模式( interpreter pattern)

发布时间:2020-12-13 16:07:51 所属栏目:PHP教程 来源:网络整理
导读:... ? php /* The interpreter pattern specifies how to evaluate language grammar or expressions.We define a representation for language grammar along with an interpreter.Representation of language grammar uses composite class hierarchy,wher

...

<?php
/*
The interpreter pattern specifies how to evaluate language grammar or expressions.
We define a representation for language grammar along with an interpreter.
Representation of language grammar uses composite class hierarchy,where rules
are mapped to classes. The interpreter then uses the representation to interpret
expressions in the language.
*/

interface MathExpression {
    public function interpret(array $values);
}

class Variable implements MathExpression {
    private $char;
    
    public function __construct($char) {
        $this->char = $char;
    }
    
    public function interpret(array $values) {
        return $values[$this->char];
    }
}

class Literal implements MathExpression {
    private $value;
    
    public function __construct($value) {
        $this->value = $value;
    }
    
    public function interpret(array $values) {
        return $this->value;
    }
}

class Sum implements MathExpression {
    private $x;
    private $y;
    
    public function __construct(MathExpression $x, 
        MathExpression $y) {
        $this->x = $x;
        $this->y = $y;
    }
    
    public function interpret(array $values) {
        return $this->x->interpret($values) + 
            $this->y->interpret($values);
    }
}

class Product implements MathExpression {
    private $x;
    private $y;
    
    public function __construct(MathExpression $x, 
        MathExpression $y) {
        $this->x = $x;
        $this->y = $y;
    }
    
    public function interpret(array $values) {
        return $this->x->interpret($values) *
            $this->y->interpret($values);
    }
}

$expression = new Product(
    new Literal(5),new Sum(
        new Variable(‘c‘),new Literal(2)
    )
);

echo $expression->interpret(array(‘c‘ => 3));
?>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读