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

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

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

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

// 上下文
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);
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值