概念
解釋器模式(Interpreter Pattern)提供了評估語言的語法或表達式的方式隅熙。這種模式實現了一個表達式接口实愚,該接口解釋一個特定的上下文。這種模式被用在 SQL 解析、符號處理引擎等守谓。
模式的場景和優(yōu)缺點
使用場景
對于一些固定文法構建一個解釋句子的解釋器
優(yōu)點
- 可擴展性比較好,靈活
- 增加了新的解釋表達式的方式
- 易于實現簡單文法
缺點
- 可利用場景比較少
- 對于復雜的文法比較難維護
- 解釋器模式會引起類膨脹
代碼實現
package main
import (
"fmt"
"strconv"
"strings"
)
// Node ...
type Node interface {
Interpret() int
}
// ValNode ...
type ValNode struct {
val int
}
// Interpret ...
func (n *ValNode) Interpret() int {
return n.val
}
// AddNode ...
type AddNode struct {
left, right Node
}
// Interpret ...
func (n *AddNode) Interpret() int {
return n.left.Interpret() + n.right.Interpret()
}
// MinNode ...
type MinNode struct {
left, right Node
}
// Interpret ...
func (n *MinNode) Interpret() int {
return n.left.Interpret() - n.right.Interpret()
}
// Parser ...
type Parser struct {
exp []string
index int
prev Node
}
// Parse ...
func (p *Parser) Parse(exp string) {
p.exp = strings.Split(exp, " ")
for {
if p.index >= len(p.exp) {
return
}
// p.prev = p.newXXX, AddNode MinNode left贤旷, 一級一級存儲上層的地址祷安,最后調用 p.Result的時候, 會依次拿到上層存儲的地址嗽桩, 拿到每一層的數據岳守。
switch p.exp[p.index] {
case "+":
p.prev = p.newAddNode()
case "-":
p.prev = p.newMinNode()
default:
p.prev = p.newValNode()
}
}
}
// newAddNode ...
func (p *Parser) newAddNode() Node {
p.index++
return &AddNode{
left: p.prev,
right: p.newValNode(),
}
}
// newMinNode ...
func (p *Parser) newMinNode() Node {
p.index++
return &MinNode{
left: p.prev,
right: p.newValNode(),
}
}
// newValNode ...
func (p *Parser) newValNode() Node {
v, _ := strconv.Atoi(p.exp[p.index])
p.index++
return &ValNode{
val: v,
}
}
// Result ...
func (p *Parser) Result() Node {
return p.prev
}
func main() {
p := &Parser{}
p.Parse("1 + 2 + 3 - 4 + 5 - 6")
// 調用 p.Result的時候, 會依次調用每一層的Interpret(), Interpret調用 left碌冶,拿到left存儲的上層地址湿痢, 拿到每一層的數據。
res := p.Result().Interpret()
fmt.Printf("res:%d\n", res)
}