-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathInterpreterPattern.md
138 lines (99 loc) · 2.89 KB
/
InterpreterPattern.md
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
130
131
132
133
134
135
136
137
138
# 解释器模式
定义一个语言的文法,并且建立一个解释器来解释该语言中的句子,这里的“语言”是指使用规定格式和语法的代码。
## 样例

如下示例简单模拟了加减乘除整数算术运算操作,使用了解释器模式:
```swift
/// 环境角色
class Context {
private var valueMap: [Character: Int] = [:]
func lookupValue(_ name: Character) -> Int {
return self.valueMap[name]!
}
func assign(variable: Variable, value: Int) {
self.valueMap[variable.name] = value
}
}
/// 抽象表达式
protocol Expression {
func interpret(context: Context) -> Int
}
/// 终结表达式
class Constant: Expression {
private var value: Int
init(_ value: Int) {
self.value = value
}
func interpret(context: Context) -> Int {
return value
}
}
class Variable:Expression {
let name: Character
init(name: Character) {
self.name = name
}
func interpret(context: Context) -> Int {
return context.lookupValue(self.name)
}
}
/// 非终结表达式
class Add: Expression {
private var left: Expression
private var right:Expression
init(left: Expression, right: Expression) {
self.left = left
self.right = right
}
func interpret(context: Context) -> Int {
return left.interpret(context: context) + right.interpret(context: context)
}
}
class Sub: Expression {
private var left: Expression
private var right:Expression
init(left: Expression, right: Expression) {
self.left = left
self.right = right
}
func interpret(context: Context) -> Int {
return left.interpret(context: context) - right.interpret(context: context)
}
}
class Mul: Expression {
private var left: Expression
private var right:Expression
init(left: Expression, right: Expression) {
self.left = left
self.right = right
}
func interpret(context: Context) -> Int {
return left.interpret(context: context) * right.interpret(context: context)
}
}
class Div: Expression {
private var left: Expression
private var right:Expression
init(left: Expression, right: Expression) {
self.left = left
self.right = right
}
func interpret(context: Context) -> Int {
return left.interpret(context: context) / right.interpret(context: context)
}
}
var a = Variable(name: "A")
var b = Variable(name: "B")
var c = Variable(name: "C")
// 创建一个表达式
var expression: Expression = Sub(left: a, right: Add(left: b, right: c)) // a - (b + c)
var context = Context()
context.assign(variable: a, value: 10)
context.assign(variable: b, value: 5)
context.assign(variable: c, value: 1)
print("结果:\(expression.interpret(context: context))")
```
结果显示:
```sh
结果:4
```