目錄
抽象工廠模式(Abstract Factory Pattern)
抽象工廠模式的核心角色
優缺點
代碼實現
抽象工廠模式(Abstract Factory Pattern)
????????抽象工廠模式(Abstract Factory Pattern)是圍繞一個超級工廠創建其他工廠。該超級工廠又稱為其他工廠的工廠。這種類型的設計模式屬于創建型模式,它提供了一種創建對象的最佳方式。在抽象工廠模式中,接口是負責創建一個相關對象的工廠,不需要顯式指定它們的類。每個生成的工廠都能按照工廠模式提供對象。抽象工廠模式提供了一種創建一系列相關或相互依賴對象的接口,而無需指定具體實現類。通過使用抽象工廠模式,可以將客戶端與具體產品的創建過程解耦,使得客戶端可以通過工廠接口來創建一族產品。
????????抽象工廠模式基于工廠方法模式。兩者的區別在于:工廠方法模式是創建出一種產品,而抽象工廠模式是創建出一類產品。這二種都屬于工廠模式,在設計上是相似的。
抽象工廠模式的核心角色
???????1、抽象工廠(Abstract Factory):聲明了一組用于創建產品對象的方法,每個方法對應一種產品類型。抽象工廠可以是接口或抽象類。
????????2、具體工廠(Concrete Factory):實現了抽象工廠接口,負責創建具體產品對象的實例。
????????3、抽象產品(Abstract Product):定義了一組產品對象的共同接口或抽象類,描述了產品對象的公共方法。
????????4、具體產品(Concrete Product):實現了抽象產品接口,定義了具體產品的特定行為和屬性。
優缺點
(1)優點:當一個產品族中的多個對象被設計成一起工作時,它能保證客戶端始終只使用同一個產品族中的對象。
(2)缺點:產品族擴展非常困難,要增加一個系列的某一產品,既要在抽象的 Creator 里加代碼,又要在具體的里面加代碼
代碼實現
package mainimport "fmt"// (抽象工廠) 能夠生產tv、手機、Ipad
type AbstractFactory interface {CreateTelevision() TelevisionCreateIpad() IpadCreateCellphone() Cellphone
}// (抽象產品) -- Television
type Television interface {Watch()
}// (抽象產品) -- Ipad
type Ipad interface {Play()
}// (抽象產品) -- Cellphone
type Cellphone interface {Callphone()
}// (具體工廠) 華為工廠
type HuaweiFactory struct {
}func (hf *HuaweiFactory) CreateTelevision() Television {return &HuaweiTelevision{}
}
func (hf *HuaweiFactory) CreateIpad() Ipad {return &HuaweiIpad{}
}
func (hf *HuaweiFactory) CreateCellphone() Cellphone {return &HuaweiCellphone{}
}// (具體產品)華為Television,實現了Television接口
type HuaweiTelevision struct {
}func (hc *HuaweiTelevision) Watch() {fmt.Println("Watch Huawei Television")
}// (具體產品)華為Ipad,實現了Ipad接口
type HuaweiIpad struct {
}func (hc *HuaweiIpad) Play() {fmt.Println("Play Huawei Ipad")
}// (具體產品)華為Cellphone,實現了Cellphone接口
type HuaweiCellphone struct {
}func (hc *HuaweiCellphone) Callphone() {fmt.Println("Call Huawei Cellphone")
}// (具體工廠) 小米工廠
type MiFactory struct {
}func (mf *MiFactory) CreateTelevision() Television {return &MiTelevision{}
}
func (mf *MiFactory) CreateIpad() Ipad {return nil
}
func (mf *MiFactory) CreateCellphone() Cellphone {return &MiCellphone{}
}// (具體產品)小米Television,實現了Television接口
type MiTelevision struct {
}func (mt *MiTelevision) Watch() {fmt.Println("Watch Mi Television")
}// (具體產品)小米Cellphone,實現了Cellphone接口
type MiCellphone struct {
}func (mc *MiCellphone) Callphone() {fmt.Println("Call Mi Cellphone")
}// 超級工廠類 獲取超級工廠實例
type HyperFactory struct {
}func (hf *HyperFactory) CreateFactory(factoryName string) AbstractFactory {switch factoryName {case "Huawei":return &HuaweiFactory{}case "Mi":return &MiFactory{}default:return nil}
}func main() {hfactoey := HyperFactory{}hwfactory := hfactoey.CreateFactory("Huawei")hwfactory.CreateTelevision().Watch()hwfactory.CreateIpad().Play()hwfactory.CreateCellphone().Callphone()mifactory := hfactoey.CreateFactory("Mi")mifactory.CreateTelevision().Watch()if mifactory.CreateIpad() == nil {fmt.Println("不支持")}mifactory.CreateCellphone().Callphone()
}