定义
给定一种语言,定义它的方法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中的句子
角色
抽象解释器(AbstractExpression):声明一个抽象解释操作
终结符表达式(TerminalExpression):实现文法中与终结符相关联的解释操作
非终结符表达式(NonterminalExpression):实现了文法中非终结符的解释操作,可用于文法中的连接符、运算符等
上下文/环境(Context):它包含了解释器之外的全局信息
优点
- 解释器是可以作为一个语法分析工具,扩展性很好,修改语法规则,只需要修改相应的终结符类就可以,如果要修改语法,则修改相应的非终结符类即可
缺点
- 语法较为复杂时,类太多
适用场景
- 重复发生的有规律的问题,如加减乘除表达式
类图
package com.vapy.behavior.Interpreter;
/**
* @author vapy 2016年8月26日
*
* 抽象解释器
*/
public abstract class AbstractExpression {
public abstract String interpret(String str);
}
package com.vapy.behavior.Interpreter;
/**
* @author vapy 2016年8月26日
*
* 终结符表达式
*/
public class Move extends AbstractExpression {
public Move() {
}
@Override
public String interpret(String distance) {
if(distance.matches("[0-9]*")){
return "move " + distance + " meters ";
}
return "move 0 meter"; //如果不是数据,移动距离算0
}
}
package com.vapy.behavior.Interpreter;
/**
* @author vapy 2016年8月26日
*
* 非终结符表达式
*/
public class And extends AbstractExpression {
public And() {
}
@Override
public String interpret(String and) {
if(and.equals("and")) {
return ",and then ";
}
return "";
}
}
package com.vapy.behavior.Interpreter;
/**
* @author vapy 2016年8月26日
*
* 上下文
*/
public class Context {
private String input;
private String output = "";
public Context(String input) {
this.input = input;
}
public void exec() {
AbstractExpression move = new Move();
AbstractExpression and = new And();
String[] in = input.split(" ");
for(String str : in) {
if(str.equalsIgnoreCase("and")) {
output += and.interpret(str);
} else {
output += move.interpret(str);
}
}
}
public String getOutput() {
return output;
}
}
package com.vapy.behavior.Interpreter;
/**
* @author vapy 2016年8月26日
*/
public class Client {
public static void main(String[] args) {
String inputExpr = "22 and 23";
Context context = new Context(inputExpr);
context.exec();
System.out.println(context.getOutput());
}
}
本文代码可在github查看:点击此处