您的位置:首页 > 编程语言 > Go语言

设计模式Go版-简单工厂

2018-01-24 17:44 162 查看

----------------simple.go-----------------

package factory

// 定义通用接口
type Operation interface {
GetResult() float64
SetNumA(float64)
SetNumB(float64)
}

// 定义通用实现类及方法
type BaseOperation struct {
numberA float64
numberB float64
}

func (self *BaseOperation) SetNumA(val float64) {
self.numberA = val
}
func (self *BaseOperation) SetNumB(val float64) {
self.numberB = val
}

// 加法操作
type OperationAdd struct {
BaseOperation
}

func (self *OperationAdd) GetResult() float64 {
return self.numberA + self.numberB
}

// 减法操作
type OperationSub struct {
BaseOperation
}

func (self *OperationSub) GetResult() float64 {
return self.numberA - self.numberB
}

// 乘法操作
type OperationMul struct {
BaseOperation
}

func (self *OperationMul) GetResult() float64 {
return self.numberA * self.numberB
}

// 除法操作
type OperationDiv struct {
BaseOperation
}

func (self *OperationDiv) GetResult() float64 {
if self.numberB == 0 {
panic("被除数不能为0")
}
return self.numberA / self.numberB
}

func CreateOperation(operation string) (op Operation) {
switch operation {
case "+":
op = new(OperationAdd)
case "-":
op = new(OperationSub)
case "/":
op = new(OperationDiv)
case "*":
op = new(OperationMul)
default:
panic("运算符错误!")
}
return
}

----------------simple_test.go-----------------

package factory

import "testing"
func TestCreateOperation(t *testing.T) {
op := CreateOperation("+")
a, b := 3.0, 2.0
op.SetNumA(a)
op.SetNumB(b)
result := op.GetResult()
if result != a+b {
t.Fatalf("%f+%f should be %f,not %f", a, b, a+b, result)
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Go 设计模式