首页 > 其他分享 >软件设计-Tutorial18

软件设计-Tutorial18

时间:2024-11-13 08:48:37浏览次数:1  
标签:distance direction String 软件设计 Tutorial18 action Expression interpret

```mermaid
classDiagram
    class Expression {
        <<interface>>
        +interpret() String
    }

    class Direction {
        -String direction
        +interpret() String
    }

    class Action {
        -String action
        +interpret() String
    }

    class Distance {
        -int distance
        +interpret() String
    }

    class SimpleExpression {
        -Expression direction
        -Expression action
        -Expression distance
        +interpret() String
    }

    class CompositeExpression {
        -List~Expression~ expressions
        +addExpression(Expression expression) void
        +interpret() String
    }

    class InterpreterContext {
        +parse(String input) Expression
    }

    Expression <|.. Direction
    Expression <|.. Action
    Expression <|.. Distance
    Expression <|.. SimpleExpression
    Expression <|.. CompositeExpression
    InterpreterContext --> CompositeExpression
    CompositeExpression o-- Expression

```
package Tutorial17;

import java.util.ArrayList;
import java.util.List;

// 1. Expression接口,定义解析接口
interface Expression {
    String interpret();
}

// 2. Direction、Action和Distance表达式类,用于解释基本指令
class Direction implements Expression {
    private String direction;

    public Direction(String direction) {
        this.direction = direction;
    }

    @Override
    public String interpret() {
        return switch (direction) {
            case "up" -> "向上";
            case "down" -> "向下";
            case "left" -> "向左";
            case "right" -> "向右";
            default -> throw new IllegalArgumentException("无效的方向: " + direction);
        };
    }
}

class Action implements Expression {
    private String action;

    public Action(String action) {
        this.action = action;
    }

    @Override
    public String interpret() {
        return switch (action) {
            case "move" -> "移动";
            case "run" -> "奔跑";
            default -> throw new IllegalArgumentException("无效的动作: " + action);
        };
    }
}

class Distance implements Expression {
    private int distance;

    public Distance(int distance) {
        this.distance = distance;
    }

    @Override
    public String interpret() {
        return distance + "个单位";
    }
}

// 3. SimpleExpression类,解释单一的方向-动作-距离指令
class SimpleExpression implements Expression {
    private Expression direction;
    private Expression action;
    private Expression distance;

    public SimpleExpression(Expression direction, Expression action, Expression distance) {
        this.direction = direction;
        this.action = action;
        this.distance = distance;
    }

    @Override
    public String interpret() {
        return direction.interpret() + action.interpret() + distance.interpret();
    }
}

// 4. CompositeExpression类,用于处理“and”复合表达式
class CompositeExpression implements Expression {
    private List<Expression> expressions = new ArrayList<>();

    public void addExpression(Expression expression) {
        expressions.add(expression);
    }

    @Override
    public String interpret() {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < expressions.size(); i++) {
            result.append(expressions.get(i).interpret());
            if (i < expressions.size() - 1) {
                result.append("再");
            }
        }
        return result.toString();
    }
}

// 5. 解释器上下文类,解析并生成对应的表达式
class InterpreterContext {
    public Expression parse(String input) {
        String[] parts = input.split(" and ");
        CompositeExpression composite = new CompositeExpression();

        for (String part : parts) {
            String[] tokens = part.split(" ");
            Expression direction = new Direction(tokens[0]);
            Expression action = new Action(tokens[1]);
            Expression distance = new Distance(Integer.parseInt(tokens[2]));
            composite.addExpression(new SimpleExpression(direction, action, distance));
        }

        return composite;
    }
}

// 6. 测试类
public class Main {
    public static void main(String[] args) {
        InterpreterContext context = new InterpreterContext();

        String input1 = "up move 5";
        Expression expression1 = context.parse(input1);
        System.out.println("输入: " + input1 + ",输出: " + expression1.interpret());

        String input2 = "down run 10 and left move 20";
        Expression expression2 = context.parse(input2);
        System.out.println("输入: " + input2 + ",输出: " + expression2.interpret());
    }
}

 

标签:distance,direction,String,软件设计,Tutorial18,action,Expression,interpret
From: https://www.cnblogs.com/muzhaodi/p/18543020

相关文章

  • 软件设计-Tutorial14
    ```mermaidclassDiagramMatchmakingService<|..RealMatchmakingServiceMatchmakingService<|..MatchmakingProxyclassMatchmakingService{+findPartner()}classRealMatchmakingService{+findPartner()}......
  • 软件设计-Tutorial13
    ```mermaidclassDiagramclassChessPiece{<<abstract>>+Stringcolor+display(intx,inty)}classWhiteChessPiece{+display(intx,inty)}classBlackChessPiece{+display(int......
  • 软件设计-Tutorial12
    packageTutorial12;//定义各个硬件设备和软件的类classMemory{publicbooleancheck(){System.out.println("Memoryself-checking...");//假设返回true表示自检成功returntrue;}}classCPU{publicbooleanrun(){......
  • 4.3软件设计:面对对象的设计
    面对对象设计1、面对对象的架构设计1.1第一步:构造系统的物理模型1.2第二步:设计子系统划分各个子系统的方式定义子系统之间的关系定义子系统的接口1.3第三步:非功能需求设计2、面对对象的用例设计与类设计2.1类2.2类间关系2.3细化用例第一步:定义类的属性第二步:定义......
  • 幼儿早教小程序软件设计与实现毕业设计源码
    博主介绍:✌专注于VUE,小程序,安卓,Java,python,物联网专业,有17年开发经验,长年从事毕业指导,项目实战✌选取一个适合的毕业设计题目很重要。✌关注✌私信我✌具体的问题,我会尽力帮助你。研究的背景:随着科技的发展和教育理念的进步,幼儿教育越来越受到重视。然而,传统的幼儿教育模......
  • 软件设计师:排序算法总结
    一、直接插入排序方式:从第一个数开始,拿两个数比较,把后面一位跟前面的数比较,把较小的数放在前面一位二、希尔排序方式:按“增量序列(步长)”分组比较,组内元素比较交换 假设初始关键字:48   37   64   96   75   12   26   58   54   3,有......
  • 软件设计-Tutorial09
    用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。类图:```mermaidclassDiagramclassRoad{<<interface>>+drive()}classCementRoad{+drive()}classAsphaltRoad{+drive()......
  • 软件设计Tutorial08
      实验8:适配器模式本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:1、理解适配器模式的动机,掌握该模式的结构;2、能够利用适配器模式解决实际问题。 [实验任务一]:双向适配器实现一个双向适配器,使得猫可以学狗叫,狗可以学猫抓老鼠。实验要求:1. 画出对应的类图;......
  • 学习高校课程-软件设计模式-责任链模式和命令模式(lec9)
    原文链接ChainofResponsibility:ProblemExample:anonlineorderingsystem示例:在线订购系统–Therequestmustpassaseriesofchecks–Newrequirements:validation,filteringrepeatedfailedrequests,speedingupbyreturningcachedresults,andmore–......
  • 学习高校课程-软件设计模式-享元模式和代理模式(lec8)
    原文链接Flyweight:ProblemEachparticle,suchasabullet,amissileorapieceofshrapnelwasrepresentedbyaseparateobjectcontainingplentyofdata.Atsomepoint,whenthecarnageonaplayer’sscreenreacheditsclimax,newlycreatedparticlesno......