go 語言沒有構(gòu)造函數(shù)一說,所以一般會定義NewXXX函數(shù)來初始化相關(guān)類。
NewXXX 函數(shù)返回接口時就是簡單工廠模式,也就是說Golang的一般推薦做法就是簡單工廠。
在這個simplefactory包中只有API 接口和NewAPI函數(shù)為包外可見,封裝了實現(xiàn)細節(jié)。
參考:Go語言中文文檔:www.topgoer.com
simple.go代碼
package simplefactory
import "fmt"
//API is interface
type API interface {
Say(name string) string
}
//NewAPI return Api instance by type
func NewAPI(t int) API {
if t == 1 {
return &hiAPI{}
} else if t == 2 {
return &helloAPI{}
}
return nil
}
//hiAPI is one of API implement
type hiAPI struct{}
//Say hi to name
func (*hiAPI) Say(name string) string {
return fmt.Sprintf("Hi, %s", name)
}
//HelloAPI is another API implement
type helloAPI struct{}
//Say hello to name
func (*helloAPI) Say(name string) string {
return fmt.Sprintf("Hello, %s", name)
}
simple_test.go代碼
package simplefactory
import "testing"
//TestType1 test get hiapi with factory
func TestType1(t *testing.T) {
api := NewAPI(1)
s := api.Say("Tom")
if s != "Hi, Tom" {
t.Fatal("Type1 test fail")
}
}
func TestType2(t *testing.T) {
api := NewAPI(2)
s := api.Say("Tom")
if s != "Hello, Tom" {
t.Fatal("Type2 test fail")
}
}