10.23

liuxuechao發表於2024-11-20

程式碼實現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);
    }
}