設計模式 | 直譯器模式及典型應用
微信原文:設計模式 | 直譯器模式及典型應用
部落格原文:設計模式 | 直譯器模式及典型應用
本文主要介紹直譯器模式,在日常開發中,直譯器模式的使用頻率比較低
直譯器模式
直譯器模式(Interpreter Pattern):定義一個語言的文法,並且建立一個直譯器來解釋該語言中的句子,這裡的 “語言” 是指使用規定格式和語法的程式碼。直譯器模式是一種類行為型模式。
角色
AbstractExpression(抽象表示式):在抽象表示式中聲明瞭抽象的解釋操作,它是所有終結符表示式和非終結符表示式的公共父類。
TerminalExpression(終結符表示式)
NonterminalExpression(非終結符表示式):非終結符表示式也是抽象表示式的子類,它實現了文法中非終結符的解釋操作,由於在非終結符表示式中可以包含終結符表示式,也可以繼續包含非終結符表示式,因此其解釋操作一般通過遞迴的方式來完成。
Context(環境類):環境類又稱為上下文類,它用於儲存直譯器之外的一些全域性資訊,通常它臨時儲存了需要解釋的語句。
示例
使用直譯器模式實現一個簡單的字尾表示式直譯器,僅支援對整數的加法和乘法即可
定義抽象表示式介面
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表示式中的直譯器模式
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設計模式精講
後記
歡迎評論、轉發、分享
更多內容可訪問我的個人部落格:http://laijianfeng.org
關注【小旋鋒】微信公眾號,及時接收博文推送