解释器模式
2018-11-02 本文已影响0人
要学的东西太多了
给定一个语言之后,解释器模式可以定义出其文法的一种表示,并同时提供一个解释器。客户端可以使用这个解释器来解释这个语言中的句子。比如一个运算表达式,数字是终结符表达式,运算符号是非终结表达式。
示例如下:
public class Expression {
public static void main(String[] a){
Expression expression=new Expression();
Context context=expression.new Context("34+2+9");
System.out.println(context.expression());
}
interface IOperation{
int expression();
}
class NumOperation implements IOperation{
private int num;
public NumOperation(int num) {
this.num = num;
}
@Override
public int expression() {
return num;
}
}
class PlusOperation implements IOperation{
private IOperation start,end;
public PlusOperation(IOperation start, IOperation end) {
this.start = start;
this.end = end;
}
@Override
public int expression() {
return start.expression()+end.expression();
}
}
class Context implements IOperation{
private Stack<NumOperation> operations=new Stack<>();
private String source;
public Context(String source) {
this.source = source;
init();
}
private void init(){
String[] strings=source.split("\\+");
for(int i=0;i<strings.length;i++){
if(operations.empty()){
operations.add(new NumOperation(Integer.valueOf(strings[i])));
}else{
operations.add(new NumOperation(new PlusOperation(operations.pop(),new NumOperation(Integer.valueOf(strings[i]))).expression()));
}
}
}
@Override
public int expression() {
return operations.pop().expression();
}
}
}