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);
    }
}
相关推荐
金銀銅鐵5 小时前
为什么枚举类中可以定义抽象方法
java·后端·ai编程
文丑颜不良啊6 小时前
LeetCode1941~1960题目解析
java·leetcode
txxzjmzlh6 小时前
SpringBoot 统⼀功能处理
java·spring boot·后端
nice_lcj5208 小时前
Java Lambda 表达式入门:怎么写、怎么用、常用方法有哪些
java·开发语言·后端·面试
码农小河669 小时前
基于SSM+JSP+MySQL的在线医疗服务系统的设计与实现
java·开发语言·mysql
SL_staff10 小时前
从配置失效到逻辑复用:JVS-Logic 如何构建可治理的业务编排中枢
java·spring·产品
特立独行的猫A10 小时前
一份 Markdown 发十个平台:cspub 一稿多投
java·后端·python
文丑颜不良啊11 小时前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊11 小时前
LeetCode2001~2020题目解析
java·leetcode
用户37215742613511 小时前
Java 批量提取 Word 文档中的图片并保存到本地
java