← 返回博客列表

模式特点

给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。

类图

类图

应用场景

示例代码(C++)

class Context {
public: std::map<std::string, bool> variables;
};

// 抽象表达式
class Expression {
public: virtual bool interpret(Context& ctx) = 0;
          virtual ~Expression() = default; };

// 终结符表达式 - 变量
class VariableExpr : public Expression {
    std::string m_name;
public:
    VariableExpr(const std::string& n) : m_name(n) {}
    bool interpret(Context& ctx) override { return ctx.variables[m_name]; }
};

// 非终结符 - AND
class AndExpr : public Expression {
    Expression* m_e1; Expression* m_e2;
public:
    AndExpr(Expression* e1, Expression* e2) : m_e1(e1), m_e2(e2) {}
    bool interpret(Context& ctx) override {
        return m_e1->interpret(ctx) && m_e2->interpret(ctx);
    }
};

// 构建表达式树: (安全IO AND 归零完成)
Expression* expr = new AndExpr(
    new VariableExpr("safety_io"),
    new VariableExpr(" homed")
);

Context ctx; ctx.variables["safety_io"] = true; ctx.variables["homed"] = true;
bool result = expr->interpret(ctx);  // true: 允许启动