File tree 3 files changed +107
-0
lines changed
3 files changed +107
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 解释器模式
2
+
3
+ 解释器模式定义一套语言文法,并设计该语言解释器,使用户能使用特定文法控制解释器行为。
4
+
5
+ 解释器模式的意义在于,它分离多种复杂功能的实现,每个功能只需关注自身的解释。
6
+
7
+ 对于调用者不用关心内部的解释器的工作,只需要用简单的方式组合命令就可以。
8
+
Original file line number Diff line number Diff line change
1
+ package interpreter
2
+
3
+ import (
4
+ "strconv"
5
+ "strings"
6
+ )
7
+
8
+ type Node interface {
9
+ Interpret () int
10
+ }
11
+
12
+ type ValNode struct {
13
+ val int
14
+ }
15
+
16
+ func (n * ValNode ) Interpret () int {
17
+ return n .val
18
+ }
19
+
20
+ type AddNode struct {
21
+ left , right Node
22
+ }
23
+
24
+ func (n * AddNode ) Interpret () int {
25
+ return n .left .Interpret () + n .right .Interpret ()
26
+ }
27
+
28
+ type MinNode struct {
29
+ left , right Node
30
+ }
31
+
32
+ func (n * MinNode ) Interpret () int {
33
+ return n .left .Interpret () - n .right .Interpret ()
34
+ }
35
+
36
+ type Parser struct {
37
+ exp []string
38
+ index int
39
+ prev Node
40
+ }
41
+
42
+ func (p * Parser ) Parse (exp string ) {
43
+ p .exp = strings .Split (exp , " " )
44
+
45
+ for {
46
+ if p .index >= len (p .exp ) {
47
+ return
48
+ }
49
+ switch p .exp [p .index ] {
50
+ case "+" :
51
+ p .prev = p .newAddNode ()
52
+ case "-" :
53
+ p .prev = p .newMinNode ()
54
+ default :
55
+ p .prev = p .newValNode ()
56
+ }
57
+ }
58
+ }
59
+
60
+ func (p * Parser ) newAddNode () Node {
61
+ p .index ++
62
+ return & AddNode {
63
+ left : p .prev ,
64
+ right : p .newValNode (),
65
+ }
66
+ }
67
+
68
+ func (p * Parser ) newMinNode () Node {
69
+ p .index ++
70
+ return & MinNode {
71
+ left : p .prev ,
72
+ right : p .newValNode (),
73
+ }
74
+ }
75
+
76
+ func (p * Parser ) newValNode () Node {
77
+ v , _ := strconv .Atoi (p .exp [p .index ])
78
+ p .index ++
79
+ return & ValNode {
80
+ val : v ,
81
+ }
82
+ }
83
+
84
+ func (p * Parser ) Result () Node {
85
+ return p .prev
86
+ }
Original file line number Diff line number Diff line change
1
+ package interpreter
2
+
3
+ import "testing"
4
+
5
+ func TestInterpreter (t * testing.T ) {
6
+ p := & Parser {}
7
+ p .Parse ("1 + 2 + 3 - 4 + 5 - 6" )
8
+ res := p .Result ().Interpret ()
9
+ expect := 1
10
+ if res != expect {
11
+ t .Fatalf ("expect %d got %d" , expect , res )
12
+ }
13
+ }
You can’t perform that action at this time.
0 commit comments