工厂模式🏭
工厂模式是一种常用的创建型设计模式。它通常用于用户需要在多个选项中进行选择的情况。
我们举个例子来理解一下。
宠物店
让我们设想一下在宠物店中如何实现这个功能。为了完全理解这一点,我们将从店主(developer
创建工厂)和顾客(user
使用接口)两个角度来分析实现过程。
业主视角
假设你是一家狗店的老板(你只把小狗送去领养)。因为你身处软件世界,所以每只狗都是Dog
你拥有的一个类的实例。现在,当顾客到来时,你只需创建一个新的实例Dog
并让他们领养它即可。🐶
不过最近,顾客们开始要求多样化。他们也在寻找领养猫咪的选择。😼
作为一个聪明的店主,你已经意识到这种需求只会越来越多样化。人们会继续期待更多样的东西。😨😤
你需要一个强大、可扩展的系统来为客户生成新的宠物
,进入工厂模式
你列出了features
宠物的所有常见特征( )。通过这些特征,你可以获取宠物的名字、发出的声音以及年龄。此列表允许你创建一个包含以下函数的接口:
type Pet interface {
GetName() string
GetAge() int
GetSound() string
}
现在,你可以创建任意数量具有相同特征的宠物了(implement the same interface
)。猫、狗、鱼、鹦鹉等等,什么都可以——只要它们实现了Pet
接口就行!😯 现在,让我们创建狗和猫:
// pet is a struct that implements Pet interface and
// would be used in any animal struct that we create.
// See `Dog` and `Cat` below
type pet struct {
name string
age int
sound string
}
func (p *pet) GetName() string {
return p.name
}
func (p *pet) GetSound() string {
return p.sound
}
func (p *pet) GetAge() int {
return p.age
}
type Dog struct {
pet
}
type Cat struct {
pet
}
你还需要一个工厂函数,根据用户的请求返回不同的宠物(狗/猫)。简单来说,如果用户想要一只狗,就给他们一只可爱的狗狗,呵呵。🙄🦮
func GetPet(petType string) Pet {
if petType == "dog" {
return &Dog{
pet{
name: "Chester",
age: 2,
sound: "bark",
},
}
}
if petType === "cat" {
return &Cat{
pet{
name: "Mr. Buttons",
age: 3,
sound: "meow",
},
}
}
}
注意,该GetPet
函数仅声明它返回的是 a Pet
,而不是明确声明的 aDog
或 a Cat
。因此,该函数可以扩展(通过编写更多实现该Pet
接口的结构体来实现)。添加更多Pet
类型不会影响那些只需要Dog
s 的现有用户。
恭喜!您已使用工厂模式创建了一家宠物商店🎉❤️
客户视角
让我们从用户的角度来看待这个问题。他们只需GetPet
使用任意配置(在本例中为type
)调用该函数即可。作为回报,他们只知道会得到一个Pet
。🤔 这在现实世界中听起来可能很奇怪,但在代码方面,最好保持抽象。😌
用户可以自由地“使用”Pet
它们。无论他们领回什么类型的宠物,这种“使用”方式都保持不变(因为所有宠物都实现了通用接口!)
让我们测试一下
func describePet(pet Pet) string {
return fmt.Sprintf("%s is %d years old. It's sound is %s", pet.GetName(), pet.GetAge(), pet.GetSound())
}
func main() {
petType := "dog"
dog := GetPet(petType)
petDescription := describePet(dog)
fmt.Println(petDescription)
fmt.Println("-------------")
petType = "cat"
cat := GetPet(petType)
petDescription = describePet(cat)
fmt.Println(petDescription)
}
输出应如下所示:
Chester is 2 years old. It's sound is bark
-------------
Mr. Buttons is 3 years old. It's sound is meow
您可以在此 GitHub 仓库中找到本教程的所有代码
希望这能让你更容易理解工厂模式🚀
干杯☕️
文章来源:https://dev.to/shubhamzanwar/factory-pattern-4hd0