一、概念
解释器模式(Interpreter Pattern):解释器模式为某个语言定义它的语法(或者叫文法)表示,并定义一个解释器用来处理这个语法。实际应用中较少用到的行为模式。
二、实现
举个常见的面试题,输入这样一个字符串“6 3 5 7 - + * ”,中间空格隔开。前面是运算的数,后面是运算符。先取前两个数6 3,再取一个运算符-,6-3=3,然后用结果继续和后面的数进行计算3+5=8,8*7=56。下面是实现代码:
1、表达式
public interface Expression {
long interpreter();
}
public class NumberExpression implements Expression{
private long number;
public NumberExpression(long number) {
this.number = number;
}
public NumberExpression(String number) {
this.number = Long.parseLong(number);
}
@Override
public long interpreter() {
return number;
}
}
public class AddExpression implements Expression {
private Expression exp1;
private Expression exp2;
public AddExpression(Expression exp1, Expression exp2) {
this.exp1 = exp1;
this.exp2 = exp2;
}
@Override
public long interpreter() {
return exp1.interpreter() + exp2.interpreter();
}
}
public class SubstractionExpression implements Expression {
private Expression exp1;
private Expression exp2;
public SubstractionExpression(Expression exp1, Expression exp2) {
this.exp1 = exp1;
this.exp2 = exp2;
}
@Override
public long interpreter() {
return exp1.interpreter() - exp2.interpreter();
}
}
public class MultiplicationExpression implements Expression {
private Expression exp1;
private Expression exp2;
public MultiplicationExpression(Expression exp1, Expression exp2) {
this.exp1 = exp1;
this.exp2 = exp2;
}
@Override
public long interpreter() {
return exp1.interpreter() * exp2.interpreter();
}
}
public class DivisionExpression implements Expression {
private Expression exp1;
private Expression exp2;
public DivisionExpression(Expression exp1, Expression exp2) {
this.exp1 = exp1;
this.exp2 = exp2;
}
@Override
public long interpreter() {
return exp1.interpreter() / exp2.interpreter();
}
}
2、ExpressionInterpreter
运算实现类
public class ExpressionInterpreter {
private Deque<Expression> numbers = new LinkedList<>();
public long interpreter(String expression) {
String[] elements = expression.split(" ");
Expression result = null;
int lastNumIndex = (elements.length + 1) / 2;
for (int i = 0; i < lastNumIndex; i++) {
numbers.addLast(new NumberExpression(elements[i]));
}
for (int j = lastNumIndex; j < elements.length; j++) {
Expression num1 = numbers.pollFirst();
Expression num2 = numbers.pollFirst();
switch (elements[j]) {
case "+":
result = new AddExpression(num1, num2);
break;
case "-":
result = new SubstractionExpression(num1, num2);
break;
case "*":
result = new MultiplicationExpression(num1, num2);
break;
case "/":
result = new DivisionExpression(num1, num2);
break;
}
long temp = result.interpreter();
numbers.addFirst(new NumberExpression(temp));
}
System.out.println("result: " + result.interpreter());
return result.interpreter();
}
3、测试类
public class Client {
public static void main(String[] args) {
ExpressionInterpreter interpreter = new ExpressionInterpreter();
interpreter.interpreter("6 3 5 7 - + *");
}
}
4、运行结果