设计模式笔记:解释器模式

解释器模式:作用于某种数据结构中的各元素的操作分离出来封装成独立的类,使其在不改变数据结构的前提下可

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

在控制小车移动的例子中,可以将小车的移动指令(如向上、向下、向左、向右)定义为一个简单的“语言”,并为每种指令创建一个解释器。下面是一个简单的C++实现,用于解释和执行这些指令。

首先,定义一个抽象表达式类Expression,它有一个纯虚函数interpret,用于解释和执行指令。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>

// 抽象表达式类
class Expression {
public:
virtual ~Expression() = default;
virtual void interpret(std::string context) = 0;
};

// 具体的表达式类,代表不同的指令
class MoveUpExpression : public Expression {
public:
void interpret(std::string context) override {
std::cout << "Car is moving up in context: " << context << std::endl;
}
};

class MoveDownExpression : public Expression {
public:
void interpret(std::string context) override {
std::cout << "Car is moving down in context: " << context << std::endl;
}
};

class MoveLeftExpression : public Expression {
public:
void interpret(std::string context) override {
std::cout << "Car is moving left in context: " << context << std::endl;
}
};

class MoveRightExpression : public Expression {
public:
void interpret(std::string context) override {
std::cout << "Car is moving right in context: " << context << std::endl;
}
};

// 上下文类,可以存储一些全局信息
class Context {
public:
std::string currentPosition = "Origin";
// 可以添加更多属性或方法
};

// 客户端代码,用于创建解释器并执行指令
int main() {
Context context;

// 创建解释器对象
std::unordered_map<std::string, std::unique_ptr<Expression>> expressionFactory = {
{"UP", std::make_unique<MoveUpExpression>()},
{"DOWN", std::make_unique<MoveDownExpression>()},
{"LEFT", std::make_unique<MoveLeftExpression>()},
{"RIGHT", std::make_unique<MoveRightExpression>()}
};

// 示例指令
std::vector<std::string> commands = {"UP", "RIGHT", "DOWN", "LEFT"};

for (const auto& command : commands) {
auto it = expressionFactory.find(command);
if (it != expressionFactory.end()) {
it->second->interpret(context.currentPosition);
// 更新当前位置(这里只是示例,实际可能需要更复杂的逻辑)
// context.currentPosition = updatePosition(context.currentPosition, command);
} else {
std::cout << "Unknown command: " << command << std::endl;
}
}

return 0;
}