go语言设计模式之interpreter

Posted aguncn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go语言设计模式之interpreter相关的知识,希望对你有一定的参考价值。

interpreter.go

package interpreter

import (
	//"fmt"
	"strconv"
	"strings"
)

const (
	SUM = "sum"
	SUB = "sub"
	MUL = "mul"
	DIV = "div"
)

type polishNotationStack []int

func (p *polishNotationStack) Push(s int) {
	*p = append(*p, s)
}

func (p *polishNotationStack) Pop() int {
	length := len(*p)

	if length > 0 {
		temp := (*p)[length-1]
		*p = (*p)[:length-1]
		return temp
	}
	return 0
}

func Calculate(o string) (int, error) {
	stack := polishNotationStack{}
	operators := strings.Split(o, " ")

	for _, operatorString := range operators {
		if isOperator(operatorString) {
			right := stack.Pop()
			left := stack.Pop()
			mathFunc := getOperationFunc(operatorString)
			res := mathFunc(left, right)
			stack.Push(res)
		} else {
			val, err := strconv.Atoi(operatorString)
			if err != nil {
				return 0, err
			}
			stack.Push(val)
		}
	}
	return int(stack.Pop()), nil
}

func isOperator(o string) bool {
	if o == SUM || o == SUB || o == MUL || o == DIV {
		return true
	}
	return false
}

func getOperationFunc(o string) func(a, b int) int {
	switch o {
	case SUM:
		return func(a, b int) int {
			return a + b
		}
	case SUB:
		return func(a, b int) int {
			return a - b
		}
	case MUL:
		return func(a, b int) int {
			return a * b
		}
	case DIV:
		return func(a, b int) int {
			return a / b
		}
	}
	return nil
}

  

interpreter_test.go

package interpreter

import (
	"testing"
)

func TestCalculate(t *testing.T) {
	tempOperation := "3 4 sum 2 sub"
	res, err := Calculate(tempOperation)

	if err != nil {
		t.Error(err)
	}

	if res != 5 {
		t.Errorf("Expected result not found: %d != %d
", 5, res)
	}

	tempOperation = "5 3 sub 8 mul 4 sum 5 div"
	res, err = Calculate(tempOperation)
	if err != nil {
		t.Error(err)
	}
	if res != 4 {
		t.Errorf("Expected result not found: %d != %d
", 4, res)
	}
}

  技术图片

 

以上是关于go语言设计模式之interpreter的主要内容,如果未能解决你的问题,请参考以下文章

Behavioral模式之Interpreter模式

设计模式之Interpreter模式(笔记)

设计模式---领域规则模式之解析器模式(Interpreter)

编程模式之Go语言如何实现装饰器

Go语言设计模式之函数式选项模式

vba interpreter 结束