您的位置:首页 > 编程语言 > PHP开发

深入PHP面向对象、模式与实践——执行及描述任务(1)

2017-04-06 21:36 651 查看

解释器模式

构造一个可以用于创建脚本化应用的迷你语言解释器。



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
ba57
, $result_l && $result_r);
}
}

$context = new InterpreterContext();
$literal = new LiteralExpression('four');
$literal->interpret($context);
print $context->lookup($literal) . "\n";
//输出four


创建了解释器模式的核心类后,解释器很容易进行扩展。但是当语言变得复杂,需要创建的类的数量会很快增加。因此解释器模式最好应用于相对小的语言。如果你需要的是一个全能的编程语言,那么最好使用第三方工具。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php