解释器模式(Interpreter):给定一个语言,定义它的文法的一种表示。解析器主要分为终结符表达式和非终结符表达式:A=B+C中B,C是终结符;+号是非终结符。
类图:
代码:
publicclass Context {
private Object context;
public Object getContext() {
returncontext;
}
publicvoid setContext(Object context) {
this.context = context;
}
}
publicinterface Expression {
publicvoid interpret(Context context);
}
publicclass TerminalExpression implements Expression {
@Override
publicvoid interpret(Context context) {
System.out.println("终端符表达式处理内容:"+context.getContext());
}
}
publicclass NonterminalExpression implements Expression {
@Override
publicvoid interpret(Context context) {
System.out.println("非终端符表达式处理内容:"+context.getContext());
}
}
publicstaticvoid main(String[] args) {
Context context=new Context();
context.setContext("speaking");
Expression e1=new TerminalExpression();
Expression e2=new NonterminalExpression();
//同样的内容用不同的解析器解析得到不一样的结果。
e1.interpret(context);
e2.interpret(context);
}
优点:扩展性强,修改语法只需修改对应的解析器类就可以。
缺点:当语法非常复杂的时候就会有难以管理。这时可以使用其他技术解决(语法分析程序)
当一个语言需要解析执行,并且你可将该语言中的句子表示为一个抽象语法树,可使用解析器模式。