php解释器模式( interpreter pattern)

该博客为转载内容,转载自https://www.cnblogs.com/aguncn/p/11184376.html ,原内容可能与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, 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));
?>

转载于:https://www.cnblogs.com/aguncn/p/11184376.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值