# 简单工厂模式--Golang版本

| -- 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 "+":
default:
calculater = new(CalculateSubtraction)
}
return calculater
}

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
}

``````

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

| -- 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 "+":
default:
calculater = new(CalculateSubtraction)
}
return calculater
}

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
}

``````