PHP设计模式之解释器模式浅析(php解析原理)学到了

随心笔谈2年前发布 admin
210 0 0

文章摘要

这篇文章介绍了使用PHP类来表示和解释逻辑表达式。文章定义了以下核心概念: 1. **抽象表达式类(AbstractExpression)**:这是一个基类,定义了`interpret()`方法,用于解释表达式并返回结果。 2. **终结符表达式类(TerminalExpression)**:继承自AbstractExpression,表示一个具体的值或符号,其`interpret()`方法返回一个布尔值。 3. **非终结符表达式类(OrExpression和AndExpression)**:分别表示逻辑“或”和“与”的运算符。它们通过继承自AbstractExpression,并在`interpret()`方法中使用运算逻辑进行计算。 4. **上下文类(Context)**:表示解释表达式时使用的上下文信息,通过`getContext()`方法获取。 文章通过示例展示了如何创建这些类实例,并调用它们的`interpret()`方法来计算逻辑表达式的值。最终输出了两个布尔结果,分别对应“或”和“与”运算的计算结果。

<?php
// 抽象表达式类
abstract class Expression
{
abstract public function interpret($context);
}
// 终结符表达式类
class TerminalExpression extends Expression
{
public function interpret($context)
{
if (strpos($context, $this->data) !==false) {
return true;
}
return false;
}
}
// 非终结符表达式类
class OrExpression extends Expression
{
protected $expr1;
protected $expr2;
public function __construct(Expression $expr1, Expression $expr2)
{
$this->expr1=$expr1;
$this->expr2=$expr2;
}
public function interpret($context)
{
return $this->expr1->interpret($context) || $this->expr2->interpret($context);
}
}
class AndExpression extends Expression
{
protected $expr1;
protected $expr2;
public function __construct(Expression $expr1, Expression $expr2)
{
$this->expr1=$expr1;
$this->expr2=$expr2;
}
public function interpret($context)
{
return $this->expr1->interpret($context) && $this->expr2->interpret($context);
}
}
// 上下文类
class Context
{
protected $context;
public function __construct($context)
{
$this->context=$context;
}
public function getContext()
{
return $this->context;
}
}
// 客户端代码
$context=new Context(“Hello, World!”);
$terminal1=new TerminalExpression(“Hello”);
$terminal2=new TerminalExpression(“World”);
$orExpression=new OrExpression($terminal1, $terminal2);
$andExpression=new AndExpression($terminal1, $terminal2);
echo $orExpression->interpret($context->getContext()) ? “True\n” : “False\n”;
echo $andExpression->interpret($context->getContext()) ? “True\n” : “False\n”;

© 版权声明

相关文章