微信原文:设计模式 | 解释器模式及典型应用
博客原文:设计模式 | 解释器模式及典型应用java
本文主要介绍解释器模式,在平常开发中,解释器模式的使用频率比较低正则表达式
解释器模式(Interpreter Pattern):定义一个语言的文法,而且创建一个解释器来解释该语言中的句子,这里的 "语言" 是指使用规定格式和语法的代码。解释器模式是一种类行为型模式。spring
AbstractExpression(抽象表达式):在抽象表达式中声明了抽象的解释操做,它是全部终结符表达式和非终结符表达式的公共父类。express
TerminalExpression(终结符表达式):终结符表达式是抽象表达式的子类,它实现了与文法中的终结符相关联的解释操做,在句子中的每个终结符都是该类的一个实例。一般在一个解释器模式中只有少数几个终结符表达式类,它们的实例能够经过非终结符表达式组成较为复杂的句子。设计模式
NonterminalExpression(非终结符表达式):非终结符表达式也是抽象表达式的子类,它实现了文法中非终结符的解释操做,因为在非终结符表达式中能够包含终结符表达式,也能够继续包含非终结符表达式,所以其解释操做通常经过递归的方式来完成。bash
Context(环境类):环境类又称为上下文类,它用于存储解释器以外的一些全局信息,一般它临时存储了须要解释的语句。微信
使用解释器模式实现一个简单的后缀表达式解释器,仅支持对整数的加法和乘法便可ide
定义抽象表达式接口工具
public interface Interpreter {
int interpret();
}
复制代码
非终结符表达式,对整数进行解释测试
public class NumberInterpreter implements Interpreter {
private int number;
public NumberInterpreter(int number) {
this.number = number;
}
public NumberInterpreter(String number) {
this.number = Integer.parseInt(number);
}
@Override
public int interpret() {
return this.number;
}
}
复制代码
终结符表达式,对加法和乘法进行解释
// 加法
public class AddInterpreter implements Interpreter {
private Interpreter firstExpression, secondExpression;
public AddInterpreter(Interpreter firstExpression, Interpreter secondExpression) {
this.firstExpression = firstExpression;
this.secondExpression = secondExpression;
}
@Override
public int interpret() {
return this.firstExpression.interpret() + this.secondExpression.interpret();
}
@Override
public String toString() {
return "+";
}
}
// 乘法
public class MultiInterpreter implements Interpreter {
private Interpreter firstExpression, secondExpression;
public MultiInterpreter(Interpreter firstExpression, Interpreter secondExpression) {
this.firstExpression = firstExpression;
this.secondExpression = secondExpression;
}
@Override
public int interpret() {
return this.firstExpression.interpret() * this.secondExpression.interpret();
}
@Override
public String toString() {
return "*";
}
}
复制代码
工具类
public class OperatorUtil {
public static boolean isOperator(String symbol) {
return (symbol.equals("+") || symbol.equals("*"));
}
public static Interpreter getExpressionObject(Interpreter firstExpression, Interpreter secondExpression, String symbol) {
if ("+".equals(symbol)) { // 加法
return new AddInterpreter(firstExpression, secondExpression);
} else if ("*".equals(symbol)) { // 乘法
return new MultiInterpreter(firstExpression, secondExpression);
} else {
throw new RuntimeException("不支持的操做符:" + symbol);
}
}
}
复制代码
测试,对后缀表达式 6 100 11 + *
进行求值
public class Test {
public static void main(String[] args) {
String inputStr = "6 100 11 + *";
MyExpressionParser expressionParser = new MyExpressionParser();
int result = expressionParser.parse(inputStr);
System.out.println("解释器计算结果: " + result);
}
}
复制代码
运行结果
入栈: 6
入栈: 100
入栈: 11
出栈: 11 和 100
应用运算符: +
阶段结果入栈: 111
出栈: 111 和 6
应用运算符: *
阶段结果入栈: 666
解释器计算结果: 666
复制代码
解释器模式为自定义语言的设计和实现提供了一种解决方案,它用于定义一组文法规则并经过这组文法规则来解释语言中的句子。虽然解释器模式的使用频率不是特别高,可是它在正则表达式、XML文档解释等领域仍是获得了普遍使用。
Spring EL表达式相关的类在 org.springframework.expression
包下,类图以下
涉及的类很是多,这里仅对此时咱们最关心的几个类作介绍:
SpelExpression,表示一个 EL 表达式,表达式在内部经过一个 AST抽象语法树 表示,EL表达式求值是经过 this.ast.getValue(expressionState);
求值
public class SpelExpression implements Expression {
private final String expression;
private final SpelNodeImpl ast;
private final SpelParserConfiguration configuration;
@Override
@Nullable
public Object getValue() throws EvaluationException {
if (this.compiledAst != null) {
try {
EvaluationContext context = getEvaluationContext();
return this.compiledAst.getValue(context.getRootObject().getValue(), context);
}
catch (Throwable ex) {
// If running in mixed mode, revert to interpreted
if (this.configuration.getCompilerMode() == SpelCompilerMode.MIXED) {
this.interpretedCount = 0;
this.compiledAst = null;
}
else {
// Running in SpelCompilerMode.immediate mode - propagate exception to caller
throw new SpelEvaluationException(ex, SpelMessage.EXCEPTION_RUNNING_COMPILED_EXPRESSION);
}
}
}
ExpressionState expressionState = new ExpressionState(getEvaluationContext(), this.configuration);
Object result = this.ast.getValue(expressionState);
checkCompile(expressionState);
return result;
}
//...省略...
}
复制代码
SpelNodeImpl:已解析的Spring表达式所表明的ast语法树的节点的通用父类型,语法树的节点在解释器模式中扮演的角色是终结符和非终结符。从类图中能够看到,SpelNodeImpl 的子类主要有 Literal,Operator,Indexer等,其中 Literal 是各类类型的值的父类,Operator 则是各类操做的父类
public abstract class SpelNodeImpl implements SpelNode, Opcodes {
protected int pos; // start = top 16bits, end = bottom 16bits
protected SpelNodeImpl[] children = SpelNodeImpl.NO_CHILDREN;
@Nullable
private SpelNodeImpl parent;
public final Object getValue(ExpressionState expressionState) throws EvaluationException {
return getValueInternal(expressionState).getValue();
}
// 抽象方法,由子类实现,获取对象的值
public abstract TypedValue getValueInternal(ExpressionState expressionState) throws EvaluationException;
//...省略...
}
复制代码
IntLiteral 表示整型文字的表达式语言的ast结点
public class IntLiteral extends Literal {
private final TypedValue value;
public IntLiteral(String payload, int pos, int value) {
super(payload, pos);
this.value = new TypedValue(value); //
this.exitTypeDescriptor = "I";
}
@Override
public TypedValue getLiteralValue() {
return this.value;
}
// ...
}
复制代码
OpPlus 表示加法的ast结点,在 getValueInternal 方法中对操做符两边进行相加操做
public class OpPlus extends Operator {
public OpPlus(int pos, SpelNodeImpl... operands) {
super("+", pos, operands);
Assert.notEmpty(operands, "Operands must not be empty");
}
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
SpelNodeImpl leftOp = getLeftOperand();
if (this.children.length < 2) { // if only one operand, then this is unary plus
Object operandOne = leftOp.getValueInternal(state).getValue();
if (operandOne instanceof Number) {
if (operandOne instanceof Double) {
this.exitTypeDescriptor = "D";
}
else if (operandOne instanceof Float) {
this.exitTypeDescriptor = "F";
}
else if (operandOne instanceof Long) {
this.exitTypeDescriptor = "J";
}
else if (operandOne instanceof Integer) {
this.exitTypeDescriptor = "I";
}
return new TypedValue(operandOne);
}
return state.operate(Operation.ADD, operandOne, null);
}
// 递归调用leftOp的 getValueInternal(state) ,获取操做符左边的值
TypedValue operandOneValue = leftOp.getValueInternal(state);
Object leftOperand = operandOneValue.getValue();
// 递归调用children[1]的 getValueInternal(state) ,获取操做符右边的值
TypedValue operandTwoValue = getRightOperand().getValueInternal(state);
Object rightOperand = operandTwoValue.getValue();
// 若是操做符左右都是数值类型,则将它们相加
if (leftOperand instanceof Number && rightOperand instanceof Number) {
Number leftNumber = (Number) leftOperand;
Number rightNumber = (Number) rightOperand;
if (leftNumber instanceof BigDecimal || rightNumber instanceof BigDecimal) {
BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class);
BigDecimal rightBigDecimal = NumberUtils.convertNumberToTargetClass(rightNumber, BigDecimal.class);
return new TypedValue(leftBigDecimal.add(rightBigDecimal));
}
else if (leftNumber instanceof Double || rightNumber instanceof Double) {
this.exitTypeDescriptor = "D";
return new TypedValue(leftNumber.doubleValue() + rightNumber.doubleValue());
}
//...省略 Float->F, BigInteger->add, Long->J,Integer->I
else {
// Unknown Number subtypes -> best guess is double addition
return new TypedValue(leftNumber.doubleValue() + rightNumber.doubleValue());
}
}
//...
return state.operate(Operation.ADD, leftOperand, rightOperand);
}
//...
}
复制代码
经过一个示例,调试查看程序中间经历的步骤
public class SpringELTest {
public static void main(String[] args) {
// 1. 构建解析器
org.springframework.expression.ExpressionParser parser = new SpelExpressionParser();
// 2. 解析表达式
Expression expression = parser.parseExpression("100 * 2 + 400 * 1 + 66");
// 3. 获取结果
int result = (Integer) expression.getValue();
System.out.println(result); // 结果:666
}
}
复制代码
EL表达式解析后获得表达式 (((100 * 2) + (400 * 1)) + 66)
若是用图形把其这棵AST抽象语法树简单地画出来,大概是这样
调用 expression.getValue()
求值,此时的 ast 是语法树的头结点,也就是 +
OpPlus,因此经过 this.ast.getValue(expressionState)
进入了 OpPlus 的 getValue 方法(是父类中的方法),接着进入 getValueInternal 方法,而后递归计算操做符左边的值,递归计算操做符右边的值,最后相加返回
参考:
刘伟.Java设计模式
Java设计模式精讲
欢迎评论、转发、分享
更多内容可访问个人我的博客:laijianfeng.org
关注【小旋锋】微信公众号,及时接收博文推送