建造者模式是一种创建型模式,用于将一个复杂对象的构建与其表示分离。在该模式中,一个单独的建造器对象负责创建与组装产品对象。在 Go 中,建造者模式经常被用于创建复杂对象,例如配置文件解析器、ORM 框架等。
下面介绍一个简单的例子,说明如何在 Go 中使用建造者模式来创建复杂对象。
假设我们要创建一个游戏角色,这个角色拥有名字、等级、装备和技能等属性。我们可以用建造者模式来创建这个角色,首先定义一个角色的接口:
type Role interface {
SetName(name string)
SetLevel(level int)
SetEquipment(equipment []string)
SetSkills(skills []string)
Show()
}
然后定义一个具体的角色结构体:
type GameRole struct {
name string
level int
equipment []string
skills []string
}
接着定义一个实现了 Role 接口的 GameRoleBuilder 结构体,这个结构体负责创建 GameRole 对象并设置其属性:
type GameRoleBuilder struct {
role *GameRole
}
func NewGameRoleBuilder() *GameRoleBuilder {
return &GameRoleBuilder{role: &GameRole{}}
}
func (b *GameRoleBuilder) SetName(name string) {
b.role.name = name
}
func (b *GameRoleBuilder) SetLevel(level int) {
b.role.level = level
}
func (b *GameRoleBuilder) SetEquipment(equipment []string) {
b.role.equipment = equipment
}
func (b *GameRoleBuilder) SetSkills(skills []string) {
b.role.skills = skills
}
func (b *GameRoleBuilder) Show() {
fmt.Printf("Name: %s, Level: %d, Equipment: %v, Skills: %v\n",
b.role.name, b.role.level, b.role.equipment, b.role.skills)
}
最后,我们可以使用 GameRoleBuilder 来创建一个 GameRole 对象:
func main() {
builder := NewGameRoleBuilder()
builder.SetName("Alice")
builder.SetLevel(10)
builder.SetEquipment([]string{"Sword", "Shield", "Armor"})
builder.SetSkills([]string{"Attack", "Defense", "Heal"})
role := builder.role
role.Show()
}
这个例子中,我们通过建造者模式将创建一个复杂的游戏角色对象的过程分解成了多个步骤,并且将具体的实现细节隐藏在了 GameRoleBuilder 中。这样,我们就可以更加灵活地创建游戏角色对象,并且在需要添加新的属性或修改构建流程时,只需要修改 GameRoleBuilder 即可,不会影响到其他代码。
我的知乎:Go 设计模式中建造者模式应用 - 知乎
如果本文对你有帮助,别忘记给我个3连 ,点赞,转发,评论。
咱们下期见!!!
收藏 等于白嫖,点赞才是真情。