1
+ package design_patterns
2
+
3
+ /* *
4
+ *
5
+ * Interpreter is a behavioral design pattern that defines a simple language grammar for a problem domain,
6
+ *
7
+ * represents grammatical rules as language sentences and interprets them to solve commonly encountered problems
8
+ *
9
+ */
10
+
11
+ // contains general information for the interpreter
12
+ class InterpreterContext {
13
+ private val variables = mutableMapOf<String , Int >()
14
+
15
+ fun putVariable (key : String , value : Int ) {
16
+ variables[key] = value
17
+ }
18
+
19
+ fun fetchVariable (key : String ): Int {
20
+ return variables[key] ? : 0
21
+ }
22
+ }
23
+
24
+ // represents a specific interpreter grammar expression
25
+ interface InterpreterExpression {
26
+ fun interpret (context : InterpreterContext )
27
+ }
28
+
29
+ class SetIntVariableExpression (
30
+ private val key : String ,
31
+ private val intValue : Int
32
+ ) : InterpreterExpression {
33
+ override fun interpret (context : InterpreterContext ) {
34
+ context.putVariable(key = key, value = intValue)
35
+ }
36
+ }
37
+
38
+ class PerformExpression (private vararg val expressions : InterpreterExpression ) : InterpreterExpression {
39
+ override fun interpret (context : InterpreterContext ) {
40
+ expressions.forEach { it.interpret(context) }
41
+ }
42
+ }
43
+
44
+ class AddVariablesExpression (
45
+ private val key0 : String ,
46
+ private val key1 : String ,
47
+ private val result : String
48
+ ) : InterpreterExpression {
49
+ override fun interpret (context : InterpreterContext ) {
50
+ context.putVariable(
51
+ key = result,
52
+ value = context.fetchVariable(key0) + context.fetchVariable(key1)
53
+ )
54
+ }
55
+ }
56
+
57
+ class MultipleVariablesExpression (
58
+ private val key0 : String ,
59
+ private val key1 : String ,
60
+ private val result : String
61
+ ) : InterpreterExpression {
62
+ override fun interpret (context : InterpreterContext ) {
63
+ context.putVariable(
64
+ key = result,
65
+ value = context.fetchVariable(key0) * context.fetchVariable(key1)
66
+ )
67
+ }
68
+ }
0 commit comments