定義:在創建一個對象時不向客戶暴露內部細節,並提供一個創建對象的通用接口。
類圖:簡單工廠把實例化的操作單獨放到一個類中,這個類就成爲簡單工廠類,讓簡單工廠類來決定應該用哪個具體子類來實例化。
這樣做能把客戶類和具體子類的實現解耦,客戶類不再需要知道有哪些子類以及應當實例化哪個子類。客戶類往往有多個,如果不使用簡單工廠,那麼所有的客戶類都要知道所有子類的細節。而且一旦子類發生改變,例如增加子類,那麼所有的客戶類都要進行修改。
案例:一個電腦產品類,被Huawei
、Apple
繼承,簡單工廠類中對電腦子類進行創建,客戶端只需要調用簡單工廠類對象創建電腦實例。
//Client
package main
func main() {
var simpleFactory = new(SimpleFactory) // 簡單工廠類
var apple Computer = simpleFactory.CreateProduct("Apple")
var huawei Computer = simpleFactory.CreateProduct("Huawei")
apple.Brand()
huawei.Brand()
}
//output
//This Computer Brand is Apple
//This Computer Brand is Huawei
//Product
package main
import "fmt"
type Computer interface { // 產品類,下面是產品類的三個子類
Brand()
}
type Apple struct {
Name string
}
func (this *Apple) Brand() {
this.Name = "Apple"
fmt.Println("This Computer Brand is ",this.Name)
}
type Huawei struct {
Name string
}
func (this *Huawei) Brand() {
this.Name = "Huawei"
fmt.Println("This Computer Brand is ",this.Name)
}
type Other struct {
Name string
}
func (this *Other) Brand() {
this.Name = "Nothing"
fmt.Println("This Computer Brand is ",this.Name)
}
//SimpleFactory
package main
type SimpleFactory struct { // 簡單工廠類
}
func (this *SimpleFactory) CreateProduct(name string) Computer {
if name == "Apple" {
return new(Apple)
} else if name == "Huawei" {
return new(Huawei)
} else {
return new(Other)
}
}