php解释器模式( interpreter pattern)

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php解释器模式( interpreter pattern)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

...

<?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));
?>

php解释器模式( interpreter pattern)

脚本宝典总结

以上是脚本宝典为你收集整理的php解释器模式( interpreter pattern)全部内容,希望文章能够帮你解决php解释器模式( interpreter pattern)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。