-
Notifications
You must be signed in to change notification settings - Fork 109
/
Interpreter.kt
68 lines (59 loc) · 1.86 KB
/
Interpreter.kt
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
package design_patterns
/**
*
* Interpreter is a behavioral design pattern that defines a simple language grammar for a problem domain,
*
* represents grammatical rules as language sentences and interprets them to solve commonly encountered problems
*
*/
// contains general information for the interpreter
class InterpreterContext {
private val variables = mutableMapOf<String, Int>()
fun putVariable(key: String, value: Int) {
variables[key] = value
}
fun fetchVariable(key: String): Int {
return variables[key] ?: 0
}
}
// represents a specific interpreter grammar expression
interface InterpreterExpression {
fun interpret(context: InterpreterContext)
}
class SetIntVariableExpression(
private val key: String,
private val intValue: Int
) : InterpreterExpression {
override fun interpret(context: InterpreterContext) {
context.putVariable(key = key, value = intValue)
}
}
class PerformExpression(private vararg val expressions: InterpreterExpression) : InterpreterExpression {
override fun interpret(context: InterpreterContext) {
expressions.forEach { it.interpret(context) }
}
}
class AddVariablesExpression(
private val key0: String,
private val key1: String,
private val result: String
) : InterpreterExpression {
override fun interpret(context: InterpreterContext) {
context.putVariable(
key = result,
value = context.fetchVariable(key0) + context.fetchVariable(key1)
)
}
}
class MultipleVariablesExpression(
private val key0: String,
private val key1: String,
private val result: String
) : InterpreterExpression {
override fun interpret(context: InterpreterContext) {
context.putVariable(
key = result,
value = context.fetchVariable(key0) * context.fetchVariable(key1)
)
}
}