给定一个语言,定义它的文法表示,并定义一个解释器,这个解释器使用该标识来解释语言中的句子。
public class Interpreter_Main {
public static void main(String[] args) {
TerminalExpression a = new TerminalExpression("a");
TerminalExpression b = new TerminalExpression("b");
TerminalExpression c = new TerminalExpression("c");
ContextMap<Integer> cmap = new ContextMap<>();
cmap.add(a,2);
cmap.add(b,4);
cmap.add(c,8);
System.out.println(new MinusOper(new PlusOper(a, b), c).interpreter(cmap));
}
}
interface Expression<T>{
//表达式
T interpreter(ContextMap<T> contextMap);
}
//抽象非终结符表达式 非终结符表达式(相当于树的树杈)
abstract class NonTerminalExpression<T> implements Expression<T>{
Expression e1,e2;
public NonTerminalExpression(Expression e1, Expression e2) {
this.e1 = e1;
this.e2 = e2;
}
}
class PlusOper extends NonTerminalExpression<Integer>{
public PlusOper(Expression e1, Expression e2) {
super(e1, e2);
}
@Override
public Integer interpreter(ContextMap<Integer> contextMap) {
Expression<Integer> expression1,expression2;
expression1 = this.e1;expression2 = this.e2;
return expression1.interpreter(contextMap) + expression2.interpreter(contextMap);
}
}
class MinusOper extends NonTerminalExpression<Integer>{
public MinusOper(Expression e1, Expression e2) {
super(e1, e2);
}
@Override
public Integer interpreter(ContextMap<Integer> contextMap) {
Expression<Integer> expression1,expression2;
expression1 = this.e1;expression2 = this.e2;
return expression1.interpreter(contextMap) - expression2.interpreter(contextMap);
}
}
//实现与文法中的元素相关联的解释操作,通常一个解释器模式中只有一个终结表达式,但有多个实例,对应不同的终结符。相当于树叶
class TerminalExpression<T> implements Expression<T>{
String variable;
public TerminalExpression(String variable) {
this.variable = variable;
}
@Override
public T interpreter(ContextMap<T> contextMap) {
return contextMap.getByExp(this);
}
}
class ContextMap<T> {
private Map<Expression,T> map = new HashMap<>();
public void add(Expression e,T o){
map.put(e,o);
}
public T getByExp(Expression e){
Expression e1;Map<Expression,T> m;
if ((m = map) != null){
e1 = e;
return m.get(e1);
}
else
return null;
}
}