umlphp
代碼實現express
<?php //interpreter.php abstract class Expression{ private static $keycount = 0; private $key; //解釋 abstract function interpret(InterpreterContext $context); function getKey(){ if(!isset($this->key)){ self::$keycount++; $this->key = self::$keycount; } return $this->key; } } abstract class OperatorExpression extends Expression{ protected $l_op; protected $l_rp; function __construct(Expression $l_op,Expression $l_rp) { $this->l_op = $l_op; $this->l_rp = $l_rp; } function interpret(InterpreterContext $context) { $this->l_op->interpret($context); $this->l_rp->interpret($context); $result_l = $context->lookup($this->l_op); $result_r = $context->lookup($this->l_rp); $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); } } // class LiteralExpression extends Expression{ private $value; function __construct($value){ $this->value = $value; } function interpret(InterpreterContext $context){ $context->replace($this,$this->value); } } //定義變量(賦值) 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; } } class InterpreterContext{ private $expressionstore = array(); function replace(Expression $exp,$value){ $this->expressionstore[$exp->getKey()] = $value; } function lookup(Expression $exp){ return $this->expressionstore[$exp->getKey()]; } } $context = new InterpreterContext(); $input = new VariableExpression('input'); $statement = new BooleanOrExpression( new EqualsExpression($input,new LiteralExpression('four')), new EqualsExpression($input,new LiteralExpression('4')) ); foreach (array('four','4','52') as $val) { $input->setValue($val); echo "$val<br>"; $statement->interpret($context); if($context->lookup($statement)){ echo "top marks<br>"; }else{ echo "dunce hat on<br>"; } } ?>
問題編程
建立解釋器模式的核心類後,解釋器很容易擴展。可是語言變得複雜是,須要建立的類的數量會很快增長。所以解釋器模式適用於相對小的語言,若是須要一個全能的編程語言,最好使用第三方工具。編程語言