软件设计 石家庄铁道大学信息学院
实验17:解释器模式(选作)
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解解释器模式的动机,掌握该模式的结构;
2、能够利用解释器模式解决实际问题。
[实验任务一]:解释器模式
某机器人控制程序包含一些简单的英文指令,其文法规则如下:
expression ::= direction action distance | composite
composite ::= expression and expression
direction ::= ‘up’ | ‘down’ | ‘left’ | ‘right’
action ::= ‘move’ | ‘run’
distance ::= an integer //一个整数值
如输入:up move 5,则输出“向上移动5个单位”;输入:down run 10 and left move 20,则输出“向下移动10个单位再向左移动20个单位”。
实验要求:
1. 提交类图;
2. 提交源代码;
// 抽象表达式接口
interface Expression {
void interpret(Context context);
}
// 方向解释类
class DirectionExpression implements Expression {
private String direction;
public DirectionExpression(String direction) {
this.direction = direction;
}
@Override
public void interpret(Context context) {
context.setDirection(direction);
}
}
// 动作解释类
class ActionExpression implements Expression {
private String action;
public ActionExpression(String action) {
this.action = action;
}
@Override
public void interpret(Context context) {
context.setAction(action);
}
}
// 距离解释类
class DistanceExpression implements Expression {
private int distance;
public DistanceExpression(int distance) {
this.distance = distance;
}
@Override
public void interpret(Context context) {
context.setDistance(distance);
}
}
import java.util.ArrayList;
import java.util.List;
// 复合表达式类
class CompositeExpression implements Expression {
private List<Expression> expressions = new ArrayList<>();
public void addExpression(Expression expression) {
expressions.add(expression);
}
@Override
public void interpret(Context context) {
for (Expression expression : expressions) {
expression.interpret(context);
}
}
}
// 上下文类
class Context {
private String direction;
private String action;
private int distance;
public void setDirection(String direction) {
this.direction = direction;
}
public void setAction(String action) {
this.action = action;
}
public void setDistance(int distance) {
this.distance = distance;
}
public String getInstruction() {
return direction + " " + action + " " + distance;
}
}
// 上下文类
class Context {
private String direction;
private String action;
private int distance;
public void setDirection(String direction) {
this.direction = direction;
}
public void setAction(String action) {
this.action = action;
}
public void setDistance(int distance) {
this.distance = distance;
}
public String getInstruction() {
return direction + " " + action + " " + distance;
}
}
public class Main {
public static void main(String[] args) {
String instruction1 = "up move 5";
Expression expression1 = InstructionParser.parse(instruction1);
Context context1 = new Context();
expression1.interpret(context1);
System.out.println("指令解析结果:" + context1.getInstruction());
String instruction2 = "down run 10 and left move 20";
Expression expression2 = InstructionParser.parse(instruction2);
Context context2 = new Context();
expression2.interpret(context2);
System.out.println("指令解析结果:" + context2.getInstruction());
}
}
3. 注意编程规范。