go-pattern-examples/behavior/08_interpreter/interpreter_caculator.go

102 lines
1.6 KiB
Go
Raw Normal View History

2020-05-04 19:01:23 +03:00
package interpreter
import (
"strconv"
"strings"
)
2020-05-05 09:44:57 +03:00
//解释自定义的加减法运算
//输入:字符串
//输出:整数值
//将一个包含加减运算的字符串,正常解析出结果
//Element 每个元素的解释接口
type Element interface {
2020-05-04 19:01:23 +03:00
Interpret() int
}
2020-05-05 09:44:57 +03:00
//ValElement 值节点
type ValElement struct {
2020-05-04 19:01:23 +03:00
val int
}
2020-05-05 09:44:57 +03:00
//Interpret 值解析单元的返回值
func (n *ValElement) Interpret() int {
2020-05-04 19:01:23 +03:00
return n.val
}
2020-05-05 09:44:57 +03:00
//AddOperate Operation(+)
type AddOperate struct {
left, right Element
2020-05-04 19:01:23 +03:00
}
2020-05-05 09:44:57 +03:00
//Interpret AddOperate
func (n *AddOperate) Interpret() int {
2020-05-04 19:01:23 +03:00
return n.left.Interpret() + n.right.Interpret()
}
2020-05-05 09:44:57 +03:00
//MinOperate Operation(-)
type MinOperate struct {
left, right Element
2020-05-04 19:01:23 +03:00
}
2020-05-05 09:44:57 +03:00
//Interpret MinOperate
func (n *MinOperate) Interpret() int {
2020-05-04 19:01:23 +03:00
return n.left.Interpret() - n.right.Interpret()
}
2020-05-05 09:44:57 +03:00
//Parser machine
2020-05-04 19:01:23 +03:00
type Parser struct {
exp []string
index int
2020-05-05 09:44:57 +03:00
prev Element
2020-05-04 19:01:23 +03:00
}
2020-05-05 09:44:57 +03:00
//Parse content
2020-05-04 19:01:23 +03:00
func (p *Parser) Parse(exp string) {
p.exp = strings.Split(exp, " ")
for {
if p.index >= len(p.exp) {
return
}
switch p.exp[p.index] {
case "+":
2020-05-05 09:44:57 +03:00
p.prev = p.newAddOperte()
2020-05-04 19:01:23 +03:00
case "-":
2020-05-05 09:44:57 +03:00
p.prev = p.newMinOperte()
2020-05-04 19:01:23 +03:00
default:
2020-05-05 09:44:57 +03:00
p.prev = p.newValElement()
2020-05-04 19:01:23 +03:00
}
}
}
2020-05-05 09:44:57 +03:00
func (p *Parser) newAddOperte() Element {
2020-05-04 19:01:23 +03:00
p.index++
2020-05-05 09:44:57 +03:00
return &AddOperate{
2020-05-04 19:01:23 +03:00
left: p.prev,
2020-05-05 09:44:57 +03:00
right: p.newValElement(),
2020-05-04 19:01:23 +03:00
}
}
2020-05-05 09:44:57 +03:00
func (p *Parser) newMinOperte() Element {
2020-05-04 19:01:23 +03:00
p.index++
2020-05-05 09:44:57 +03:00
return &MinOperate{
2020-05-04 19:01:23 +03:00
left: p.prev,
2020-05-05 09:44:57 +03:00
right: p.newValElement(),
2020-05-04 19:01:23 +03:00
}
}
2020-05-05 09:44:57 +03:00
func (p *Parser) newValElement() Element {
2020-05-04 19:01:23 +03:00
v, _ := strconv.Atoi(p.exp[p.index])
p.index++
2020-05-05 09:44:57 +03:00
return &ValElement{
2020-05-04 19:01:23 +03:00
val: v,
}
}
2020-05-05 09:44:57 +03:00
//Result of parsing result
func (p *Parser) Result() Element {
2020-05-04 19:01:23 +03:00
return p.prev
}