PHP设计模式之解释器(Interpreter)模式入门与应用(2)

同样,当包含一个解释器时,复合模式的叶子和容器参与者名称会不一样,这些名称反映了它们所扮演的角色:终结符(terminal)或非终结符(nonterminal)表达式。

来看下参与者:

◆客户端(Client):使用解释操作。
◆抽象表达式(AbstractExpression):基于一个表达式树抽象。
◆非终结符表达式(NonTerminalExpression):递归地包含其它抽象表达式(AbstractExpression实例)的表达式。
◆终结符表达式(TerminalExpression):不能够进一步简化的表达式。

我们来看下《设计模式》一书针对这个模式提供的一个扩展示例,是一个网友使用数学表达式替换布尔表达式重新改造了一下,因此这个例子解决了一个数学表达式的展现,它的evaluate( )被分离在一个不同的ConcreteExpression类中,如下:

/** 
 * AbstractExpression. All implementations of this interface 
 * are ConcreteExpressions. 
 */ 
interface MathExpression 
{ 
 /** 
  * Calculates the value assumed by the expression. 
  * Note that $values is passed to all expression but it 
  * is used by Variable only. This is required to abstract 
  * away the tree structure. 
  */ 
 public function evaluate(array $values); 
} 
 
/** 
 * A terminal expression which is a literal value. 
 */ 
class Literal implements MathExpression 
{ 
 private $_value; 
 
 public function __construct($value) 
 { 
  $this->_value = $value; 
 } 
 
 public function evaluate(array $values) 
 { 
  return $this->_value; 
 } 
} 
 
/** 
 * A terminal expression which represents a variable. 
 */ 
class Variable implements MathExpression 
{ 
 private $_letter; 
 
 public function __construct($letter) 
 { 
  $this->_letter = $letter; 
 } 
 
 public function evaluate(array $values) 
 { 
  return $values[$this->_letter]; 
 } 
} 
 
/** 
 * Nonterminal expression. 
 */ 
class Sum implements MathExpression 
{ 
 private $_a; 
 private $_b; 
 
 public function __construct(MathExpression $a, MathExpression $b) 
 { 
  $this->_a = $a; 
  $this->_b = $b; 
 } 
 
 public function evaluate(array $values) 
 { 
  return $this->_a->evaluate($values) + $this->_b->evaluate($values); 
 } 
} 
 
/** 
 * Nonterminal expression. 
 */ 
class Product implements MathExpression 
{ 
 private $_a; 
 private $_b; 
 
 public function __construct(MathExpression $a, MathExpression $b) 
 { 
  $this->_a = $a; 
  $this->_b = $b; 
 } 
 
 public function evaluate(array $values) 
 { 
  return $this->_a->evaluate($values) * $this->_b->evaluate($values); 
 } 
} 
 
// 10(a + 3) 
$expression = new Product(new Literal(10), new Sum(new Variable('a'), new Literal(3))); 
echo $expression->evaluate(array('a' => 4)), "\n"; 
// adding new rules to the grammar is easy: 
// e.g. Power, Subtraction... 
// thanks to the Composite, manipulation is even simpler: 
// we could add substitute($letter, MathExpression $expr) 
// to the interface... 


      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/3956.html