解释器模式
构造一个可以用于创建脚本化应用的迷你语言解释器。
abstract class Expression
{
private static $keycount = 0;
private $key;
abstract function interpret(InterpreterContext $context);
function getKey()
{
if (!asset($this->key)) {
self::$keycount++;
$this->key = self::$keycount;
}
return $this->key;
}
}
class LiteralExpression extends Expression
{
private $value;
function __construct($value)
{
$this->value = $value;
}
function interpret(InterpreterContext $context)
{
$context->replace($this, $this->value);
}
}
class InterpreterContext
{
private $expressionstore = array();
function replace(Expression $exp, $value)
{
$this->expressionstore[$exp->getKey()] = $value;
}
function lookup(Expression $exp)
{
return $this->expressionstore[$exp->getKey()];
}
}
class VariableExpression extends Expression
{
private $name;
private $val;
function __construct($name, $val = null)
{
$this->name = $name;
$this->val = $val;
}
function interpret(InterpreterContext $context)
{
if (!is_null($this->val)) {
$context->replace($this, $this->val);
$this->val = null;
}
}
function setValue($value)
{
$this->val = $value;
}
function getKey()
{
return $this->name;
}
}
abstract class OperatorExpression extends Expression
{
protected $l_op;
protected $r_op;
function __construct(Expression $l_op, Expression $r_op)
{
$this->l_op = $l_op;
$this->r_op = $r_op;
}
function interpret(InterpreterContext $context)
{
$this->l_op->interpret($context);
$this->r_op->interpret($context);
$result_l = $context->lookup($this->l_op);
$result_r = $context->lookup($this->r_op);
$this->doInterpret($context, $result_l, $result_r);
}
protected abstract function doInterpret(InterpreterContext $context, $result_l, $result_r);
}
class EqualsExpression extends OperatorExpression
{
protected function doInterpret(InterpreterContext $context, $result_l, $result_r)
{
$context->replace($this, $result_l == $result_r);
}
}
class BooleanOrExpression extends OperatorExpression
{
protected function doInterpret(InterpreterContext $context, $result_l, $result_r)
{
$context->replace($this, $result_l || $result_r);
}
}
class BooleanAndExpression extends OperatorExpression
{
protected function doInterpret(InterpreterContext $context, $result_l, $result_r)
{
$context->replace($this, $result_l && $result_r);
}
}
$context = new InterpreterContext();
$literal = new LiteralExpression('four');
$literal->interpret($context);
print $context->lookup($literal) . "\n";
//输出four
创建了解释器模式的核心类后,解释器很容易进行扩展。但是当语言变得复杂,需要创建的类的数量会很快增加。因此解释器模式最好应用于相对小的语言。如果你需要的是一个全能的编程语言,那么最好使用第三方工具。
本文介绍了解释器模式的实现方式,通过构建核心类创建了一个简单的迷你语言解释器。该模式适用于脚本化应用,但更适合于规模较小的语言。
1万+

被折叠的 条评论
为什么被折叠?



