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

随心笔谈9个月前发布 admin
224 00
🌐 经济型:买域名、轻量云服务器、用途:游戏 网站等 《腾讯云》特点:特价机便宜 适合初学者用 点我优惠购买
🚀 拓展型:买域名、轻量云服务器、用途:游戏 网站等 《阿里云》特点:中档服务器便宜 域名备案事多 点我优惠购买
🛡️ 稳定型:买域名、轻量云服务器、用途:游戏 网站等 《西部数码》 特点:比上两家略贵但是稳定性超好事也少 点我优惠购买

文章摘要

这篇文章介绍了一种基于面向对象的表达式解析系统,通过定义多个类实现了逻辑运算的结构化表示和评估。核心内容如下: 1. **表达式类**:定义了抽象类`Expression`,其子类`TerminalExpression`、`OrExpression`和`AndExpression`分别表示终端符、逻辑“或”和逻辑“与”表达式。 2. **继承与运算**:`OrExpression`和`AndExpression`通过继承实现了运算符的逻辑运算功能,分别使用“或”(`||`)和“与”(`&&`)操作符。 3. **上下文机制**:通过`Context`类传递语境信息,`interpret`方法将表达式与上下文结合,进行逻辑运算评估。 4. **客户端代码**:展示了如何构建表达式树并调用`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”;

© 版权声明

相关文章