Java23种设计模式-行为型模式之解释器模式

解释器模式(Interpreter Pattern):定义了一种文法,并且对于任何该文法的句子,都能够解释和执行。可以将复杂的问题分解成一系列简单的表达式,然后使用解释器来解释这些表达式。

涉及角色
抽象表达式(Abstract Expression):定义一个抽象的解释操作,通常包含一个interpret()方法,用于解释语句。
终结符表达式(Terminal Expression):实现抽象表达式中的interpret()方法,表示语言中的终结符。
非终结符表达式(Non-terminal Expression):实现抽象表达式中的interpret()方法,表示语言中的非终结符。
上下文(Context):包含解释器解释的信息的类。
客户端(Client):创建并配置表达式的类。

示例:定义了抽象表达式Expression、终结符表达式NumberExpression、非终结符表达式AddExpression以及上下文Context。通过这些类的协作,我们可以解释一个简单的加法表达式,并输出计算结果

java 复制代码
// 上下文
public class Context {
    private String input;
    private int output;

    public Context(String input) {
        this.input = input;
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

    public int getOutput() {
        return output;
    }

    public void setOutput(int output) {
        this.output = output;
    }
}
// 抽象表达式
interface Expression {
    int interpret(Context context);
}
// 终结符表达式
class NumberExpression implements Expression {
    private int number;

    public NumberExpression(int number) {
        this.number = number;
    }

    @Override
    public int interpret(Context context) {
        return number;
    }
}
// 非终结符表达式
class AddExpression implements Expression {
    private Expression left;
    private Expression right;

    public AddExpression(Expression left, Expression right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public int interpret(Context context) {
        return left.interpret(context) + right.interpret(context);
    }
}
// 客户端
public class InterpreterPatternTest {
    public static void main(String[] args) {
        Context context = new Context("1 + 2 + 3");
        
        Expression expression = new AddExpression(new NumberExpression(1), new AddExpression(new NumberExpression(2), new NumberExpression(3)));
        
        int result = expression.interpret(context);
        
        System.out.println("Result: " + result);
    }
}
相关推荐
飛_1 小时前
解决VSCode无法加载Json架构问题
java·服务器·前端
木棉软糖4 小时前
一个MySQL的数据表最多能够存多少的数据?
java
程序视点4 小时前
Java BigDecimal详解:小数精确计算、使用方法与常见问题解决方案
java·后端
愿你天黑有灯下雨有伞4 小时前
Spring Boot SSE实战:SseEmitter实现多客户端事件广播与心跳保活
java·spring boot·spring
Java初学者小白5 小时前
秋招Day20 - 微服务
java
狐小粟同学6 小时前
JavaEE--3.多线程
java·开发语言·java-ee
KNeeg_6 小时前
Spring循环依赖以及三个级别缓存
java·spring·缓存
AI_Gump7 小时前
【AI阅读】20250717阅读输入
java·spring boot·spring
找不到、了8 小时前
Java排序算法之<插入排序>
java·算法·排序算法
设计师小聂!8 小时前
力扣热题100----------53最大子数组和
java·数据结构·算法·leetcode