簡(jiǎn)介
簡(jiǎn)單工廠模式又稱為靜態(tài)工廠模式,屬于創(chuàng)建型模式,但不屬于GOF23設(shè)計(jì)模式。由一個(gè)工廠對(duì)象決定創(chuàng)建出哪一種產(chǎn)品類的實(shí)例。簡(jiǎn)單工廠模式的實(shí)質(zhì)是由一個(gè)工廠類根據(jù)傳入的參數(shù),動(dòng)態(tài)決定應(yīng)該創(chuàng)建哪一個(gè)產(chǎn)品類。
簡(jiǎn)單工廠適用場(chǎng)景:工廠類負(fù)責(zé)創(chuàng)建的對(duì)象比較少;客戶端只需要知道傳入工廠類的參數(shù),對(duì)于如何創(chuàng)建對(duì)象的邏輯并不關(guān)心。
簡(jiǎn)單工廠優(yōu)缺點(diǎn):
- 優(yōu)點(diǎn):只需要傳入一個(gè)正確的參數(shù),就可以獲取你所需要的對(duì)象,而無(wú)需知道其細(xì)節(jié)創(chuàng)建。
- 缺點(diǎn):工廠類的職責(zé)相對(duì)過重,增加新的產(chǎn)品,需要修改工廠類的判斷邏輯,違背了開閉原則。
示例代碼
Go
go
語(yǔ)言沒有構(gòu)造函數(shù),所以一般會(huì)定義NewXXX
函數(shù)來(lái)初始化相關(guān)類。NewXXX
函數(shù)返回接口時(shí)就是簡(jiǎn)單工廠模式,也就是說Go
的一般推薦做法就是簡(jiǎn)單工廠,
simplefactory/demo.go
package simplefactory
import "fmt"
type API interface {
Say(name string) string
}
func NewAPI(t int) API {
if t == 1 {
return &hiAPI{}
} else if t == 2 {
return &helloAPI{}
}
return nil
}
type hiAPI struct{}
func (*hiAPI) Say(name string) string {
return fmt.Sprintf("hi, %s", name)
}
type helloAPI struct {}
func (*helloAPI) Say(name string) string {
return fmt.Sprintf("hello, %s", name)
}
單元測(cè)試:simplefactory/demo_test.go
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-831262.html
package simplefactory
import (
"testing"
)
func TestType1(t *testing.T) {
api := NewAPI(1)
s := api.Say("zhangsan")
if s != "hi, zhangsan" {
t.Error("test failed")
}
}
func TestType2(t *testing.T) {
api := NewAPI(2)
s := api.Say("zhangsan")
if s != "hello, zhangsan" {
t.Error("test failed")
}
}
主方法調(diào)用 main.go
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-831262.html
package main
import (
"fmt"
"tmpgo/simplefactory"
)
func main() {
api := simplefactory.NewAPI(1)
fmt.Println(api.Say("zhangsan"))
}
Python
class GreetAPI:
def Say(self, name):
pass
class HiAPI(GreetAPI):
def Say(self, name):
return f"Hi, {name}"
class helloAPI(GreetAPI):
def Say(self, name):
return f"Hello, {name}"
def NewGreetAPI(t: int):
if t == 1:
return HiAPI()
elif t == 2:
return helloAPI()
else:
raise Exception(f"Unknown type: {t}")
if __name__ == "__main__":
api = NewGreetAPI(2)
print(api.Say("zhangsan"))
參考
- 博客園 - kasamino - 設(shè)計(jì)模式之工廠模式
到了這里,關(guān)于[設(shè)計(jì)模式]創(chuàng)建型模式-簡(jiǎn)單工廠模式的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!