C++实现设计模式---解释器模式 (Interpreter Pattern)
#include <iostream>
#include <string>
#include <memory>
#include <unordered_map>
// 抽象表达式
class Expression {
public:
virtual ~Expression() = default;
// 解释方法
virtual int interpret(const std::unordered_map<std::string, int>& context) const = 0;
};
// 终结符表达式:变量
class VariableExpression : public Expression {
private:
std::string name;
public:
explicit VariableExpression(std::string name) : name(std::move(name)) {}
int interpret(const std::unordered_map<std::string, int>& context) const override {
auto it = context.find(name);
if (it != context.end()) {
return it->second; // 返回变量的值
}
throw std::runtime_error("变量未定义: " + name);
}
};
// 终结符表达式:常量
class ConstantExpression : public Expression {
private:
int value;
public:
explicit ConstantExpression(int value) : value(value) {}
int interpret(const std::unordered_map<std::string, int>& context) const override {
return value; // 返回常量值
}
};
// 非终结符表达式:加法
class AddExpression : public Expression {
private:
std::shared_ptr<Expression> left;
std::shared_ptr<Expression> right;
public:
AddExpression(std::shared_ptr<Expression> left, std::shared_ptr<Expression> right)
: left(std::move(left)), right(std::move(right)) {}
int interpret(const std::unordered_map<std::string, int>& context) const override {
return left->interpret(context) + right->interpret(context); // 加法操作
}
};
// 非终结符表达式:减法
class SubtractExpression : public Expression {
private:
std::shared_ptr<Expression> left;
std::shared_ptr<Expression> right;
public:
SubtractExpression(std::shared_ptr<Expression> left, std::shared_ptr<Expression> right)
: left(std::move(left)), right(std::move(right)) {}
int interpret(const std::unordered_map<std::string, int>& context) const override {
return left->interpret(context) - right->interpret(context); // 减法操作
}
};
// 客户端代码
int main() {
// 构建表达式: (x + 10) - y
auto x = std::make_shared<VariableExpression>("x");
auto y = std::make_shared<VariableExpression>("y");
auto constant = std::make_shared<ConstantExpression>(10);
auto addExpr = std::make_shared<AddExpression>(x, constant); // x + 10
auto subtractExpr = std::make_shared<SubtractExpression>(addExpr, y); // (x + 10) - y
// 上下文
std::unordered_map<std::string, int> context = {{"x", 5}, {"y", 3}};
// 解释表达式
std::cout << "表达式结果: " << subtractExpr->interpret(context) << "
"; // 输出结果: 12
return 0;
}