实验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. 提交源代码;
3. 注意编程规范。
1.
2.// 抽象表达式
interface Expression {
void interpret(String command);
}
// 方向终结符表达式
class Direction implements Expression {
public void interpret(String command) {
// 解释方向命令
System.out.print(command + " ");
}
}
// 动作终结符表达式
class Action implements Expression {
public void interpret(String command) {
// 解释动作命令
System.out.print(command + " ");
}
}
// 距离终结符表达式
class Distance implements Expression {
public void interpret(String command) {
// 解释距离命令
System.out.println(command + "个单位");
}
}
// 复合表达式
class Composite implements Expression {
private List<Expression> expressions = new ArrayList<>();
public void addExpression(Expression expr) {
expressions.add(expr);
}
public void interpret(String command) {
for (Expression expr : expressions) {
expr.interpret(command);
}
}
}
// 上下文
class Context {
public String getCommand() {
// 返回当前命令
return "up move 5";
}
}
// 客户端
public class Client {
public static void main(String[] args) {
Context context = new Context();
Expression expression = new Composite();
expression.addExpression(new Direction());
expression.addExpression(new Action());
expression.addExpression(new Distance());
// 解释命令
expression.interpret(context.getCommand());
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端