Functional Options Pattern,选项模式
1、什么是选项模式
选项模式是一种在 Go 语言中很常用的设计模式,特别是当你有一个结构体或函数,并且它有多个可选的配置选项时。该模式允许用户提供一系列的的函数来设置结构体的属性或修改函数的行为。
2、为什么使用选项模式
- 灵活性:可以选择设置某些选项,而忽略其他选项。
- 代码整洁:减少常参数列表和大量构造函数/方法的需要。
- 扩展性强:可以很容易的添加新的选择,而不影响原有代码。
- 明确性高:通过名称化的函数调用,意图更加明确。
3、如何实现
a. 定义函数类型
函数类型定义了如何修改目标对象。这是提供自定义逻辑的关键。
type CarOption func(*Car)
b. 为每个选项创建函数
每个函数都会返回上述定义的函数类型。
func WithColor(color string) CarOption {
return func(c *Car) {
c.Color = color
}
}
c. 在构造函数中应用选项
创建一个函数,该函数接受上述选项并应用它们来配置目标对象。
func NewCar(opts ...CarOption) *Car {
car := &Car{}
for _, opt := range opts {
opt(car)
}
return car
}
4、范例
type Cat struct {
Color string
Age int
}
type CatOption func(*Cat)
// 每个 With 返回一个 option
func WithColor(color string) CatOption {
return func(cat *Cat) {
cat.Color = color
}
}
func WithAge(age int) CatOption {
return func(cat *Cat) {
cat.Age = age
}
}
// New 函数遍历执行 option
func NewCat(option ...CatOption) *Cat {
c := &Cat{}
for _, v := range option {
v(c)
}
return c
}
// 主函数
func main() {
cat := NewCat(WithColor("red"), WithAge(2))
fmt.Println(cat)
}