Go实现工厂模式

80 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第1天,点击查看活动详情

优点:

  1. 不需要记住具体类名,甚至连具体参数都不用记忆。
  2. 实现了对象创建和使用的分离。
  3. 系统的可扩展性也就变得非常好,无需修改接口和原类。
  4. 对于新产品的创建,符合开闭原则。

代码实现

 package abstractfactory
 
 import "fmt"
 
 type Fruit interface {
     Show()
 }
 
 type Factory interface {
     CreateFruit() Fruit
 }
 
 // apple
 type Apple struct{}
 
 func (a *Apple) Show() {
     fmt.Println("我是苹果")
 }
 
 type AppleFactory struct{}
 
 func (af *AppleFactory) CreateFruit() Fruit {
     return new(Apple)
 }
 
 // Banana
 type Banana struct{}
 
 func (a *Banana) Show() {
     fmt.Println("我是香蕉")
 }
 
 type BananaFactory struct{}
 
 func (af *BananaFactory) CreateFruit() Fruit {
     return new(Banana)
 }
 
 // Pear
 type Pear struct{}
 
 func (a *Pear) Show() {
     fmt.Println("我是梨")
 }
 
 type PearFactory struct{}
 
 func (af *PearFactory) CreateFruit() Fruit {
     return new(Pear)
 }

符合开闭原则。如果需要加入新的水果。只需要在后面加入就可以:

 // strawberry
 type Strawberry struct{}
 
 func (a *Strawberry) Show() {
     fmt.Println("我是草莓")
 }
 
 type StrawberryFactory struct{}
 
 func (af *StrawberryFactory) CreateFruit() Fruit {
     return new(Strawberry)
 }