golang设计模式--工厂方法

87 阅读1分钟

1.前提:

需要先了解简单工厂的来龙去脉,下面附上简单工厂的代码

type animal interface{}
type dog struct{}
type cat struct{}
type duck struct{}

func NewExample(name string) animal {
 switch name {
 case "dog":
    return &dog{}
 case "cat":
    return &cat{}
 case "duck":
    return &duck{}
 }
 return nil

}
type breeder struct{}
func (b *breeder) NewExample(name string) animal {
   switch name {
   case "dog":
      return &dog{}
   case "cat":
      return &cat{}
   case "duck":
      return &duck{}
   }
   return nil

}

2.工厂方法

很容易分析出来,简单工厂是不符合开闭原则的,所以这也是为什么它不属于 23 种设计模式
根据开闭原则特点,需要把函数提到接口里面,所以基于此,出现了工厂方法

package main

type animal interface{}
type dog struct{}
type cat struct{}
type duck struct{}

type NewExampleFactory interface {
   NewExample() animal
}
type dogNewExampleFactory struct {
}
type catNewExampleFactory struct {
}
type duckNewExampleFactory struct {
}

func (d *dogNewExampleFactory) NewExample() animal {
   return &dog{}

}
func (c *catNewExampleFactory) NewExample() animal {
   return &cat{}

}
func (d *duckNewExampleFactory) NewExample() animal {
   return &duck{}

}
func main() {

}

粗略一看,感觉和抽象工厂是很像的:
工厂方法在思想上更加的强调一个实例化函数就只能拿一种实例化对象
抽象工厂,则侧重的是含有 switch-case 结构的情况,强调结构体可以拿到多种的实例化