GO 实现工厂模式实现加减乘除的计算

今天闲来无事,在学习GO的时候,写了一个工厂类~

// author      : Aaron zhang
// date        : 2021/6/26 14:27
// description :  func 类型的使用

package main

import "fmt"

type Factory interface {
	calc(int, int) int
}

//加法
type Plus struct {
}

func (p *Plus) calc(a, b int) int {
	return a + b
}

//减法
type Reduce struct {
}

func (r *Reduce) calc(a, b int) int {
	return a - b
}

//乘法
type Time struct {
}

func (t *Time) calc(a, b int) int {
	return a * b
}

//除法
type Division struct {
}

func (d *Division) calc(a, b int) int {
	return a / b
}

func Calculation(factory Factory, a, b int) int {
	return factory.calc(a, b)
}
func useWho(act string, a, b int) int {
	res := 0
	switch act {
	case "+":
		res = Calculation(&Plus{}, a, b)
	case "-":
		res = Calculation(&Reduce{}, a, b)
	case "*":
		res = Calculation(&Time{}, a, b)
	case "/":
		res = Calculation(&Division{}, a, b)
	}
	return res
}
func main() {
	fmt.Println(useWho("+", 20, 21))
	fmt.Println(useWho("-", 20, 21))
	fmt.Println(useWho("*", 20, 21))
	fmt.Println(useWho("/", 433, 21))

}

 

0

1 thought on “GO 实现工厂模式实现加减乘除的计算”

发表评论

邮箱地址不会被公开。