标签:
定义:给定一门语言,定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言的句子
类图:
代码:
public abstract class Expression { public abstract Object interpreter(Context ctx); }
public class TerminalExpression extends Expression{ @Override public Object interpreter(Context ctx) { // TODO Auto-generated method stub return null; } }
public class NonterminalExpression extends Expression{ public NonterminalExpression(Expression ... expressions){ } @Override public Object interpreter(Context ctx) { // TODO Auto-generated method stub return null; } }
public abstract class Expression { public abstract Object interpreter(HashMap<String,Integer> var); }
public class VarExpression extends Expression{ private String key; public VarExpression(String key){ this.key = key; } @Override public Object interpreter(HashMap<String, Integer> var) { // TODO Auto-generated method stub return var.get(key); } }
public abstract class SymbolExpression extends Expression{ protected Expression left; protected Expression right; public SymbolExpression(Expression left,Expression right){ this.left = left; this.right = right; } }
public class AddExpression extends SymbolExpression{ public AddExpression(Expression left, Expression right) { super(left, right); // TODO Auto-generated constructor stub } @Override public int interpreter(HashMap<String, Integer> var) { // TODO Auto-generated method stub return super.left.interpreter(var) + super.right.interpreter(var); } }
public class SubExpression extends SymbolExpression{ public SubExpression(Expression left, Expression right) { super(left, right); // TODO Auto-generated constructor stub } @Override public int interpreter(HashMap<String, Integer> var) { // TODO Auto-generated method stub return super.left.interpreter(var) - super.right.interpreter(var); } }
public class Calculator { private Expression expression; public Calculator(String expStr){ Stack<Expression> stack = new Stack<Expression>(); char[] charArray = expStr.toCharArray(); Expression left = null; Expression right = null; for(int i = 0; i<charArray.length;i++){ switch(charArray[i]){ case'+': left = stack.pop(); right = new VarExpression(String.valueOf(charArray[i])); stack.push(new AddExpression(left,right)); break; case'-': left = stack.pop(); right = new VarExpression(String.valueOf(charArray[i])); stack.push(new SubExpression(left,right)); break; default: stack.push(new VarExpression(String.valueOf(charArray[i]))); } } this.expression = stack.pop(); } public int run(HashMap<String,Integer> var){ return this.expression.interpreter(var); } }
扩展性,修改语法规则只需修改相应的非终结符表达式
缺点:
解释器模式引起类的膨胀
效率问题
一般不加以使用
标签:
原文地址:http://blog.csdn.net/renpengddxx/article/details/52151746