解释器模式(Interpreter Pattern)提供了评估语言的语法或表达式的方式,它属于行为型模式。这种模式实现了一个表达式接口,该接口解释一个特定的上下文。这种模式被用在 SQL 解析、符号处理引擎等。
Class Diagram
Implementation
表达式接口
1 2 3
| public interface Expression { public int interpret(); }
|
非终结表达式(操作符表达式)
1 2 3 4 5 6 7 8
| public abstract class NonTerminalExpression implements Expression { Expression e1,e2;
public NonTerminalExpression(Expression e1, Expression e2) { this.e1 = e1; this.e2 = e2; } }
|
1 2 3 4 5 6 7 8 9 10 11
| public class PlusExpression extends NonTerminalExpression{ public PlusExpression(Expression e1, Expression e2) { super(e1, e2); }
@Override public int interpret() { return this.e1.interpret() + this.e2.interpret(); } }
|
1 2 3 4 5 6 7 8 9 10 11
| public class MinusExpression extends NonTerminalExpression { public MinusExpression(Expression e1, Expression e2) { super(e1, e2); }
@Override public int interpret() { return this.e1.interpret() - this.e2.interpret(); }
}
|
终结表达式(数据表达式)
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class TerminalExpression implements Expression{
String value;
public TerminalExpression(String value) { this.value = value; }
@Override public int interpret() { return Integer.parseInt(value); } }
|
增加表达式解析器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public final class ExpressionParser {
public static Expression parse(String expr){ Expression expression = null; for(int i=0;i<expr.length();i++){ char ch = expr.charAt(i); switch(ch){ case '+': expression = new PlusExpression(expression,new TerminalExpression(String.valueOf(expr.charAt(++i)))); break; case '-': expression = new MinusExpression(expression,new TerminalExpression(String.valueOf(expr.charAt(++i)))); break; default: expression = new TerminalExpression(String.valueOf(ch)); } } return expression; } }
|
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class InterpreterTest {
@Test public void test() throws Exception { TerminalExpression s3 = new TerminalExpression("333"); TerminalExpression s5 = new TerminalExpression("555"); TerminalExpression s8 = new TerminalExpression("888");
int result = new MinusExpression(new PlusExpression(s3,s8),s5).interpret(); System.out.println(result); }
@Test public void test2() throws Exception{ Expression exp = ExpressionParser.parse("3+8-5"); int result = exp.interpret(); System.out.println(result); } }
|
Example
Refence