设计模式——抽象工厂
先用一个需求引入工厂模式
这里我们的需求就是,按照不同的种类,生成不同种类的对象,当然,我们可以设计九个类,对应不同种类的对象,但是如果每次添加新的产品,我们可能就要修改核心代码,这样会引出一个解决方法——抽象工厂
抽象工厂
对于生成这类的对象,他们有共同点还有不同点,不同种类的风格,但是可以生成同一类产品,那么我们可以先声明不同物品要实现的接口,然后每个工厂生产这个对象都要实现这个接口。
我们使用go来实现。
package main type PublicFunction interface { HasLegs() int } type IChair interface { PublicFunction IsSitDown() bool } type ITable interface { PublicFunction IsFull() bool } type ISofa interface { PublicFunction IsFull() bool } type Factory interface { MakeChair() IChair MakeTable() ITable MakeSofa() ISofa } func GetFactory(brand string) Factory { if brand == "modern" { return ModernFactory{ } } return ModernFactory{ } } type Chair struct { Part string LegsNumber int SitDown bool } func (c Chair) HasLegs() int { return c.LegsNumber } func (c Chair) IsSitDown() bool { return c.SitDown } type Table struct { Part string LegsNumber int Full bool } func (t Table) HasLegs() int { return t.LegsNumber } func (t Table) IsFull() bool { return t.Full } type Sofa struct { Part string LegsNumber int Full bool } func (s Sofa) HasLegs() int { return s.LegsNumber } func (s Sofa) IsFull() bool { return s.Full } type ModernFactory struct { } func (m ModernFactory) MakeChair() IChair { return Chair{ SitDown: false, LegsNumber: 4, Part: "modern"} } func (m ModernFactory) MakeTable() ITable { return Table{ LegsNumber: 4, Full: false, Part: "modern"} } func (m ModernFactory) MakeSofa() ISofa { return Sofa{ Full: false, Part: "modern", LegsNumber: 4} } func main() { factory := GetFactory("modern") sofa := factory.MakeSofa() fmt.Printf("the sofa is full ? %t ,the sofa has %d legs ", sofa.IsFull(), sofa.HasLegs()) }
适用性:
-
一个系统要独立于它的产品的创建、组合和表示 要强调一系列相关的产品对象的设计以便进行联合使用
总结:
- 根据我们需要的模型,我们需要横向建立接口(Factory接口)纵向建立接口(Chair、Table、Sofa)
- 返回的类型一般是接口,一般不会是结构体,通过接口操作结构体。