Golang的工厂模式可以应用于以下场景:
创建对象时需要根据不同的条件返回不同的具体对象实例。需要隐藏对象创建的具体过程,只暴露一个工厂方法给外部调用。需要通过一个共享的工厂来创建多个相似的对象。以下是一个示例代码:
package mainimport "fmt"// 定义一个接口type Animal interface {Sound() string}// 定义具体的狗类type Dog struct{}func (d Dog) Sound() string {return "汪汪汪"}// 定义具体的猫类type Cat struct{}func (c Cat) Sound() string {return "喵喵喵"}// 定义工厂函数,根据传入的参数返回相应的具体对象实例func AnimalFactory(animalType string) Animal {switch animalType {case "dog":return Dog{}case "cat":return Cat{}default:return nil}}func main() {dog := AnimalFactory("dog")fmt.Println(dog.Sound()) // 输出:汪汪汪cat := AnimalFactory("cat")fmt.Println(cat.Sound()) // 输出:喵喵喵}在上述示例中,我们定义了一个Animal接口和两个具体的实现类Dog和Cat。然后通过工厂函数AnimalFactory根据传入的参数返回相应的具体对象实例。最后在main函数中使用工厂函数创建不同类型的动物对象并调用其方法。

