定义:一种按照规定语法进行解析的方案
类图:
角色
1.AbstractExpression抽象解释器:具体的解释任务由各个实现类完成,具体的解释器分别由TerminalExpression和 NonterminalExpression 2.TerminalExpression终结符表达式:实现与文法中的元素相关联的解释操作,通常一个解释器模式中只有一个终结 表达式,但有多个实例,对应不同的终结符。 3.NonterminalExpression非终结符表达式:文法中的每条规则对应于一个非终结表达式,非终结符表达式根据逻辑的 复杂程度而增加,原则上每个文法规则都对应一个非终结符表达式 4.Context环境角色
实例:
解释乘法 3 * 2
public interface Node { public int interpret(); } public class ValueNode implements Node{ private int value; public ValueNode(int value) { this.value=value; } public int interpret() { return this.value; } } public abstract class SymbolNode implements Node{ protected Node left; protected Node right; public SymbolNode(Node left,Node right) { this.left=left; this.right=right; } } public class MulNode extends SymbolNode { public MulNode(Node left,Node right) { super(left,right); } public int interpret() { return left.interpret() * right.interpret(); } } public class Calculator{ private String statement; private Node node; public void build(String statement){ Node left=null,right=null; Stack stack=new Stack(); String[] statementArr=statement.split(" "); for(int i=0;i<statementArr.length;i++){ if(statementArr[i].equalsIgnoreCase("*")){ left=(Node)stack.pop(); int val=Integer.parseInt(statementArr[++i]); right=new ValueNode(val); stack.push(new MulNode(left,right)); } else{ stack.push(new ValueNode(Integer.parseInt(statementArr[i]))); } } this.node=(Node)stack.pop(); } public int compute() { return node.interpret(); } } public class Client { public static void main(String args[]){ String statement = "3 * 2"; Calculator calculator = new Calculator(); calculator.build(statement); int result = calculator.compute(); System.out.println(statement + " = " + result); } } 运算结果