11.20日报
今天完成设计模式实验十七,以下为今日实验内容:
实验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. 提交源代码;
- import java.util.Stack;
// 上下文环境
class Context {
private String command;
public Context(String command) {
this.command = command;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
}
// 表达式接口
interface Expression {
String interpret(Context context);
}
// 终结符表达式
abstract class TerminalExpression implements Expression {
}
// 方向表达式
class DirectionExpression extends TerminalExpression {
@Override
public String interpret(Context context) {
String direction = context.getCommand().split(" ")[0];
return direction;
}
}
// 动作表达式
class ActionExpression extends TerminalExpression {
@Override
public String interpret(Context context) {
String action = context.getCommand().split(" ")[1];
return action;
}
}
// 距离表达式
class DistanceExpression extends TerminalExpression {
@Override
public String interpret(Context context) {
String[] parts = context.getCommand().split(" ");
int distance = Integer.parseInt(parts[2]);
return String.valueOf(distance);
}
}
// 复合表达式
class CompositeExpression implements Expression {
private Expression firstExpression;
private Expression secondExpression;
public CompositeExpression(Expression firstExpression, Expression secondExpression) {
this.firstExpression = firstExpression;
this.secondExpression = secondExpression;
}
@Override
public String interpret(Context context) {
String first = firstExpression.interpret(context);
String second = secondExpression.interpret(new Context(context.getCommand().split(" and ")[1]));
return first + "再" + second;
}
}
// 非终结符表达式
class ExpressionParser {
public String parse(String command) {
String[] parts = command.split(" and ");
Expression first = new CompositeExpression(
new DirectionExpression(),
new CompositeExpression(new ActionExpression(), new DistanceExpression())
);
Expression second = new CompositeExpression(
new DirectionExpression(),
new CompositeExpression(new ActionExpression(), new DistanceExpression())
);
return new CompositeExpression(first, second).interpret(new Context(parts[0] + " and " + parts[1]));
}
}
// 客户端
public class InterpreterPatternExample {
public static void main(String[] args) {
String command1 = "up move 5";
String command2 = "down run 10 and left move 20";
ExpressionParser parser = new ExpressionParser();
System.out.println("命令:" + command1 + ",输出:" + "向上移动5个单位");
System.out.println("命令:" + command2 + ",输出:" + parser.parse(command2));
}
}
3. 注意编程规范。