Skip to content

解释器模式 (Interpreter Pattern)

解释器模式是什么?

解释器模式(Interpreter Pattern)是一种行为型设计模式,它定义了如何对一门小型语言写下的句子进行求值。文法中的每一条规则都变成一个类,程序通过遍历这些类构成的树来对句子求值。

核心思想:每条语法规则一个类——表达式树通过递归对自己求值。

为什么需要解释器模式?

问题场景

假设你正在为一个规则引擎编写一门小型表达式语言。第一个版本只有三种运算,写起来很容易:

// Problem: one class carries parsing, evaluation and printing
class ExpressionEvaluator {
public:
    int evaluate(const std::string& expression) const {
        // every new operation means a new branch here, another one in
        // describe(), and another one in the parser
        if (expression == "1 + 2") {
            return 3;
        }
        if (expression == "3 * 4") {
            return 12;
        }
        if (expression == "x + 1") {
            return 10 + 1;
        }
        return 0;
    }

    std::string describe(const std::string& expression) const {
        if (expression == "1 + 2") {
            return "(1 + 2)";
        }
        if (expression == "3 * 4") {
            return "(3 * 4)";
        }
        return expression;
    }
};

问题:

  1. 每增加一种运算,每个函数里都要多加一个分支
  2. 求值器、打印器和解析器渐渐各行其是
  3. 规则无法组合——"1 + 2" 无法嵌套进另一条规则中

解决方案

使用解释器模式:给文法中的每条规则配一个自己的类,让这些类递归地对自己求值。

// The context holds the variables that the expression reads
class Context;

// The abstract expression: one operation, the same for every node
class Expression {
public:
    virtual ~Expression() = default;
    virtual int interpret(const Context& context) const = 0;
    virtual std::string toString() const = 0;
};

// A concrete expression: the sum of two expressions
class AddExpression : public Expression {
public:
    AddExpression(std::shared_ptr<Expression> left, std::shared_ptr<Expression> right)
        : left_(std::move(left)), right_(std::move(right)) {}

    int interpret(const Context& context) const override {
        return left_->interpret(context) + right_->interpret(context);
    }

    std::string toString() const override {
        return "(" + left_->toString() + " + " + right_->toString() + ")";
    }

private:
    std::shared_ptr<Expression> left_;
    std::shared_ptr<Expression> right_;
};

优点:

  1. 文法变成一个类层次,每条规则对应一个类
  2. 新增运算就是新增一个类,而不是在已有函数里多加一个分支
  3. 求值是递归且统一的:客户端只需要调用 interpret()

模式结构

                    ┌──────────────────┐
                    │      Client      │
                    └────────┬─────────┘
                             │ builds
                    ┌────────▼─────────┐
                    │     Expression   │ ← abstract expression
                    └────────┬─────────┘
                             │
           ┌─────────────────┼─────────────────┐
           │                 │                 │
  ┌────────▼────────┐ ┌──────▼───────┐ ┌───────▼────────┐
  │ Number          │ │ Variable     │ │ Add            │
  │ (terminal)      │ │ (terminal)   │ │ (composite)    │
  └─────────────────┘ └──────────────┘ └───────┬────────┘
                                                 │ children
                                        ┌────────▼────────┐
                                        │    Expression   │
                                        └─────────────────┘
┌──────────┐   the variables   ┌──────────────────────────┐
│ Context  │ ────────────────► │  Expression::interpret() │
└──────────┘                   └────────────┬─────────────┘
                                             │ recurses into the children
                                   ┌─────────▼─────────┐
                                   │    Expression     │
                                   └───────────────────┘

代码实现

1. 定义表达式接口与上下文

#include <memory>
#include <string>
#include <map>
#include <iostream>

// The context holds the variables that the expression reads
class Context {
public:
    void set(const std::string& name, int value) {
        variables_[name] = value;
    }

    int get(const std::string& name) const {
        auto it = variables_.find(name);
        return it != variables_.end() ? it->second : 0;
    }

private:
    std::map<std::string, int> variables_;
};

// The abstract expression: one operation, the same for every node
class Expression {
public:
    virtual ~Expression() = default;
    virtual int interpret(const Context& context) const = 0;
    virtual std::string toString() const = 0;
};

2. 实现终结符表达式

// A leaf: a literal number
class NumberExpression : public Expression {
public:
    explicit NumberExpression(int value) : value_(value) {}

    int interpret(const Context& context) const override {
        (void)context;  // a number ignores the context
        return value_;
    }

    std::string toString() const override {
        return std::to_string(value_);
    }

private:
    int value_;
};

// A leaf: a variable that is looked up in the context
class VariableExpression : public Expression {
public:
    explicit VariableExpression(std::string name) : name_(std::move(name)) {}

    int interpret(const Context& context) const override {
        return context.get(name_);
    }

    std::string toString() const override {
        return name_;
    }

private:
    std::string name_;
};

3. 实现非终结符表达式

// A composite: the sum of two expressions
class AddExpression : public Expression {
public:
    AddExpression(std::shared_ptr<Expression> left, std::shared_ptr<Expression> right)
        : left_(std::move(left)), right_(std::move(right)) {}

    int interpret(const Context& context) const override {
        return left_->interpret(context) + right_->interpret(context);
    }

    std::string toString() const override {
        return "(" + left_->toString() + " + " + right_->toString() + ")";
    }

private:
    std::shared_ptr<Expression> left_;
    std::shared_ptr<Expression> right_;
};

// A composite: the product of two expressions
class MultiplyExpression : public Expression {
public:
    MultiplyExpression(std::shared_ptr<Expression> left, std::shared_ptr<Expression> right)
        : left_(std::move(left)), right_(std::move(right)) {}

    int interpret(const Context& context) const override {
        return left_->interpret(context) * right_->interpret(context);
    }

    std::string toString() const override {
        return "(" + left_->toString() + " * " + right_->toString() + ")";
    }

private:
    std::shared_ptr<Expression> left_;
    std::shared_ptr<Expression> right_;
};

4. 构建并求值表达式树

int main() {
    // The tree for (3 + 4) * 2
    auto add = std::make_shared<AddExpression>(
        std::make_shared<NumberExpression>(3),
        std::make_shared<NumberExpression>(4)
    );
    auto tree = std::make_shared<MultiplyExpression>(
        add,
        std::make_shared<NumberExpression>(2)
    );

    std::cout << "Expression: " << tree->toString() << "\n";
    std::cout << "Result: " << tree->interpret(Context{}) << "\n";

    // The tree for x + y, evaluated with a context
    Context context;
    context.set("x", 10);
    context.set("y", 5);

    auto sum = std::make_shared<AddExpression>(
        std::make_shared<VariableExpression>("x"),
        std::make_shared<VariableExpression>("y")
    );

    std::cout << "With variables: " << sum->toString()
              << " = " << sum->interpret(context) << "\n";

    return 0;
}

现代 C++ 实现

使用 std::variant 和 std::visit

#include <map>
#include <memory>
#include <string>
#include <type_traits>
#include <variant>

struct Add;
struct Multiply;

// A node is a number, a variable name, or a composite node
using Expression = std::variant<int,
                                std::string,
                                std::shared_ptr<Add>,
                                std::shared_ptr<Multiply>>;

struct Add {
    Expression left;
    Expression right;
};

struct Multiply {
    Expression left;
    Expression right;
};

int interpret(const Expression& expression, const std::map<std::string, int>& variables);

int interpret(const Expression& expression, const std::map<std::string, int>& variables) {
    return std::visit([&](const auto& node) -> int {
        using Node = std::decay_t<decltype(node)>;

        if constexpr (std::is_same_v<Node, int>) {
            return node;
        } else if constexpr (std::is_same_v<Node, std::string>) {
            auto it = variables.find(node);
            return it != variables.end() ? it->second : 0;
        } else if constexpr (std::is_same_v<Node, std::shared_ptr<Add>>) {
            return interpret(node->left, variables) + interpret(node->right, variables);
        } else {
            return interpret(node->left, variables) * interpret(node->right, variables);
        }
    }, expression);
}

用模板表示运算符

// One template replaces every binary operation
template<typename Op>
class BinaryExpression : public Expression {
public:
    BinaryExpression(std::shared_ptr<Expression> left, std::shared_ptr<Expression> right)
        : left_(std::move(left)), right_(std::move(right)) {}

    int interpret(const Context& context) const override {
        return Op{}(left_->interpret(context), right_->interpret(context));
    }

    std::string toString() const override {
        return "(" + left_->toString() + " " + Op::symbol() + " " + right_->toString() + ")";
    }

private:
    std::shared_ptr<Expression> left_;
    std::shared_ptr<Expression> right_;
};

struct AddOp {
    int operator()(int a, int b) const { return a + b; }
    static const char* symbol() { return "+"; }
};

struct MultiplyOp {
    int operator()(int a, int b) const { return a * b; }
    static const char* symbol() { return "*"; }
};

// The tree is now built with
// std::make_shared<BinaryExpression<AddOp>>(left, right)

用 std::function 擦除节点类型

#include <functional>

// The node type is erased: the tree becomes a tree of callables
using Node = std::function<int(const Context&)>;

Node number(int value) {
    return [value](const Context&) { return value; };
}

Node variable(std::string name) {
    return [name = std::move(name)](const Context& context) {
        return context.get(name);
    };
}

Node add(Node left, Node right) {
    return [left = std::move(left), right = std::move(right)](const Context& context) {
        return left(context) + right(context);
    };
}

与相关模式的区别

模式 区别
策略模式 策略模式在运行时挑选一种算法;解释器模式定义一门小型语言并递归地对它求值
解释器 vs 解析器 解析器负责构建语法树,解释器负责对树求值;两者通常一起使用
解释器 vs 访问者 访问者遍历的是已经存在的结构;解释器模式把结构和操作一起定义出来

最佳实践

1. 让语法与类层次保持同步

// The grammar of the language:
//
//   expression := term (('+' | '-') term)*
//   term       := factor (('*' | '/') factor)*
//   factor     := NUMBER | VARIABLE | '(' expression ')'
//
// One class per rule, and the hierarchy mirrors the grammar:
//
//   Expression
//   ├── NumberExpression      (factor)
//   ├── VariableExpression    (factor)
//   ├── AddExpression         (expression)
//   ├── SubtractExpression    (expression)
//   ├── MultiplyExpression    (term)
//   └── DivideExpression      (term)

2. 把解析与求值分开

// The parser builds the tree, the interpreter evaluates it
class Parser {
public:
    explicit Parser(std::string text) : text_(std::move(text)) {}

    std::shared_ptr<Expression> parse() const {
        // a real parser tokenizes the text and builds the tree
        return std::make_shared<NumberExpression>(0);
    }

private:
    std::string text_;
};

// The client uses the two in turn
Context context;
context.set("x", 10);

auto tree = Parser("3 + 4 * 2").parse();
std::cout << tree->interpret(context) << "\n";

3. 让树拥有自己的子节点

// Recommended: shared_ptr lets every node own its children
auto add = std::make_shared<AddExpression>(
    std::make_shared<NumberExpression>(3),
    std::make_shared<NumberExpression>(4)
);

auto tree = std::make_shared<MultiplyExpression>(
    add,
    std::make_shared<NumberExpression>(2)
);

// The same tree is evaluated with different contexts
Context context;
context.set("x", 10);

std::cout << tree->interpret(context) << "\n";

常见陷阱

陷阱 1:上下文被忽略

// Not recommended: the node keeps its own copy of the value
class VariableExpression : public Expression {
public:
    explicit VariableExpression(std::string name, int value)
        : name_(std::move(name)), value_(value) {}

    int interpret(const Context& context) const override {
        (void)context;      // the context is ignored
        return value_;      // the value was frozen when the tree was built
    }

    std::string toString() const override {
        return name_;
    }

private:
    std::string name_;
    int value_;
};

// Recommended: read the value from the context at evaluation time
class VariableExpression : public Expression {
public:
    explicit VariableExpression(std::string name) : name_(std::move(name)) {}

    int interpret(const Context& context) const override {
        return context.get(name_);
    }

    std::string toString() const override {
        return name_;
    }

private:
    std::string name_;
};

陷阱 2:未知变量悄悄变成零

// Not recommended: a typo in a variable name is invisible
int get(const std::string& name) const {
    auto it = variables_.find(name);
    return it != variables_.end() ? it->second : 0;
}

// Recommended: report the missing variable
int get(const std::string& name) const {
    auto it = variables_.find(name);
    if (it == variables_.end()) {
        throw std::runtime_error("unknown variable: " + name);
    }
    return it->second;
}

陷阱 3:树不是不可变的

// Not recommended: the evaluation changes the tree it walks
class AccumulateExpression : public Expression {
public:
    explicit AccumulateExpression(std::shared_ptr<Expression> left)
        : left_(std::move(left)) {}

    int interpret(const Context& context) const override {
        total_ += left_->interpret(context);  // the node keeps a running total
        return total_;
    }

    std::string toString() const override {
        return left_->toString();
    }

private:
    std::shared_ptr<Expression> left_;
    mutable int total_ = 0;
};

// Evaluating the same tree twice gives two different answers

示例

这个主题的可运行版本:

总结

解释器模式的核心要点:

  • 适用场景:一门小型语言、一套稳定的文法、由语言自身定义的那些运算
  • 核心优点:文法变成类层次,新增一条规则就是新增一个类,求值方式始终统一
  • 实现要点:把解析与求值分开,把变量集中放进一个上下文,让 shared_ptr 拥有这棵树
  • 常见陷阱:上下文被忽略、未知变量悄悄变成零、求值过程中树被改写

记住:解释器模式的关键是每条语法规则一个类——表达式树通过递归对自己求值。

另请参阅