10.23

代码实现Context 类的作用

// Context 类
class Context {
    private int variable;

    public void setVariable(int value) {
        this.variable = value;
    }

    public int getVariable() {
        return variable;
    }
}

// 抽象表达式
interface Expression {
    int interpret(Context context);
}

// 终结符表达式
class NumberExpression implements Expression {
    private int number;

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

    public int interpret(Context context) {
        return number;
    }
}

// 非终结符表达式
class MultiplyExpression implements Expression {
    private Expression left;
    private Expression right;

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

    public int interpret(Context context) {
        int leftValue = left.interpret(context);
        int rightValue = right.interpret(context);
        return leftValue * rightValue;
    }
}

// 客户端代码
public class InterpreterPatternExample {
    public static void main(String[] args) {
        // 创建 Context 对象
        Context context = new Context();

        // 设置上下文中的变量值
        context.setVariable(5);

        // 构建解释器的语法树
        Expression expression = new MultiplyExpression(
            new NumberExpression(10),
            new NumberExpression(2)
        );

        // 解释并获取结果
        int result = expression.interpret(context);
        System.out.println("Result: " + result);
    }
}
 
posted @ 2024-11-20 10:18  liuxuechao  阅读(2)  评论(0编辑  收藏  举报