目录结构:
| -- calculater-simpleFactory
| -- main.go
| -- Calculater
| | -- Calculater.go
- main.go
package main
import (
"calculater-simpleFactory/Calculater"
"fmt"
)
func main() {
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
opreate := Calculater.NewCalculate("+")
sum, _ := opreate.Opreation(numbers)
fmt.Println("sum = ", sum)
opreate2 := Calculater.NewCalculate("-")
res, _ := opreate2.Opreation(numbers)
fmt.Println("res = ", res)
}
Calculater.go
/*
* @Description:
* @Author: huacong
* @Date: 2020-03-22 17:33:43
* @LastEditTime: 2020-03-22 18:26:28
* @LastEditors: huacong
*/
package Calculater
import (
"errors"
"fmt"
)
//计算器接口
type Calculater interface {
Opreation(numbers []int) (int, error)
}
func NewCalculate(opreate string) Calculater {
var calculater Calculater
switch opreate {
case "+":
calculater = new(CalculateAdd)
default:
calculater = new(CalculateSubtraction)
}
return calculater
}
type CalculateAdd struct{}
func (*CalculateAdd) Opreation(numbers []int) (int, error) {
if len(numbers) < 2 {
return 0, errors.New("运算数字不能少于2个")
}
sum := 0
for _, v := range numbers {
sum += v
}
return sum, nil
}
type CalculateSubtraction struct{}
func (*CalculateSubtraction) Opreation(numbers []int) (int, error) {
if len(numbers) < 2 {
return 0, errors.New("运算数字不能少于2个")
}
sum := numbers[0]
for i := 1; i < len(numbers); i++ {
fmt.Println(sum - numbers[i])
sum -= numbers[i]
}
return sum, nil
}
有疑问加站长微信联系(非本文作者)