1.1. 模式動(dòng)機(jī)
考慮一個(gè)簡(jiǎn)單的軟件應(yīng)用場(chǎng)景誓军,一個(gè)軟件系統(tǒng)可以提供多個(gè)外觀不同的按鈕(如圓形按鈕巾腕、矩形按鈕、菱形按鈕等)闪湾, 這些按鈕都源自同一個(gè)基類冲甘,不過(guò)在繼承基類后不同的子類修改了部分屬性從而使得它們可以呈現(xiàn)不同的外觀,如果我們希望在使用這些按鈕時(shí)响谓,不需要知道這些具體按鈕類的名字损合,只需要知道表示該按鈕類的一個(gè)參數(shù),并提供一個(gè)調(diào)用方便的方法娘纷,把該參數(shù)傳入方法即可返回一個(gè)相應(yīng)的按鈕對(duì)象,此時(shí)跋炕,就可以使用簡(jiǎn)單工廠模式赖晶。
1.2. 模式定義
簡(jiǎn)單工廠模式(Simple Factory Pattern):又稱為靜態(tài)工廠方法(Static Factory Method)模式,它屬于類創(chuàng)建型模式。在簡(jiǎn)單工廠模式中遏插,可以根據(jù)參數(shù)的不同返回不同類的實(shí)例捂贿。簡(jiǎn)單工廠模式專門定義一個(gè)類來(lái)負(fù)責(zé)創(chuàng)建其他類的實(shí)例,被創(chuàng)建的實(shí)例通常都具有共同的父類胳嘲。
1.3. 模式結(jié)構(gòu)
簡(jiǎn)單工廠模式包含如下角色:
-
Factory:工廠角色
工廠角色負(fù)責(zé)實(shí)現(xiàn)創(chuàng)建所有實(shí)例的內(nèi)部邏輯
-
Product:抽象產(chǎn)品角色
抽象產(chǎn)品角色是所創(chuàng)建的所有對(duì)象的父類厂僧,負(fù)責(zé)描述所有實(shí)例所共有的公共接口
-
ConcreteProduct:具體產(chǎn)品角色
具體產(chǎn)品角色是創(chuàng)建目標(biāo),所有創(chuàng)建的對(duì)象都充當(dāng)這個(gè)角色的某個(gè)具體類的實(shí)例了牛。
./images/SimpleFactory.jpg
1.4. 代碼分析
go 語(yǔ)言沒(méi)有構(gòu)造函數(shù)一說(shuō)颜屠,所以一般會(huì)定義NewXXX函數(shù)來(lái)初始化相關(guān)類。 NewXXX 函數(shù)返回接口時(shí)就是簡(jiǎn)單工廠模式鹰祸,也就是說(shuō)Golang的一般推薦做法就是簡(jiǎn)單工廠甫窟。
在這個(gè)simplefactory包中只有API 接口和NewAPI函數(shù)為包外可見(jiàn),封裝了實(shí)現(xiàn)細(xì)節(jié)蛙婴,如下:
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)
}
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")
}
}