Repository navigation
Expand file tree
/
Copy pathInterpreterPattern.h
More file actions
129 lines (121 loc) · 2.42 KB
/
Copy pathInterpreterPattern.h
File metadata and controls
129 lines (121 loc) · 2.42 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#ifndef __INTERPRETOR_PATTERN_H__
#define __INTERPRETOR_PATTERN_H__
#include <vector>
using namespace std;
// 抽象表达式类
class AbstractNode
{
public:
AbstractNode(){}
// 声明抽象接口
virtual char interpret() = 0;
};
// 终结符表达式:ValueNode
class ValueNode :public AbstractNode
{
public :
ValueNode(){}
ValueNode(int iValue){
this->value = iValue;
}
// 实现解释操作
char interpret(){
return value;
}
private:
int value;
};
// 终结符表达式:OperationNode
class OperatorNode :public AbstractNode
{
public:
OperatorNode(){}
OperatorNode(string iOp){
this->op = iOp;
}
// 实现解释操作
char interpret(){
if (op == "and"){
return '&';
}
else if (op == "or"){
return '|';
}
return 0;
}
private:
string op;
};
// 非终结符表达式:SentenceNode
class SentenceNode :public AbstractNode
{
public:
SentenceNode(){}
SentenceNode(AbstractNode *iLeftNode,
AbstractNode *iRightNode, AbstractNode* iOperatorNode){
this->leftNode = iLeftNode;
this->rightNode = iRightNode;
this->operatorNode = iOperatorNode;
}
char interpret(){
if (operatorNode->interpret() == '&'){
return leftNode->interpret()&rightNode->interpret();
}
else{
return leftNode->interpret()|rightNode->interpret();
}
return 0;
}
private:
AbstractNode *leftNode;
AbstractNode *rightNode;
AbstractNode *operatorNode;
};
// 处理者
class Handler
{
public:
Handler(){}
void setInput(string iInput){
this->input = iInput;
}
void handle(){
AbstractNode *left = NULL;
AbstractNode *right = NULL;
AbstractNode *op = NULL;
AbstractNode *sentence = NULL;
string iInput = this->input;
vector<string>inputList;
char* inputCh = const_cast<char*>(iInput.c_str());
char *token = strtok(inputCh, " ");
while (token != NULL){
inputList.push_back(token);
token = strtok(NULL, " ");
}
for (int i = 0; i < inputList.size() - 2; i += 2){
left = new ValueNode(*(inputList[i].c_str()));
op = new OperatorNode(inputList[i + 1]);
right = new ValueNode(*(inputList[i+2].c_str()));
sentence = new SentenceNode(left, right, op);
inputList[i + 2] = string(1, sentence->interpret());
}
string tmpRes = inputList[inputList.size() - 1];
if (tmpRes == "1"){
result = 1;
}
else if (tmpRes == "0"){
result = 0;
}
else{
result = -1;
}
this->output();
}
void output(){
printf("%s = %d\n", input.c_str(), result);
}
private:
string input;
char result;
};
#endif //__INTERPRETOR_PATTERN_H__