設計模式Go版-簡單工廠

----------------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)
   }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章