更好的创建构造函数的方式

在Golang里,不支持函数重载,那么带来了一个问题。怎么创建多个可选参数的构造构造函数?

通常我们的构造函数时这样子的:

 

1 type Student struct {
2     Name string
3 }
4 
5 func NewStudent (name string) *Student{
6     return &Student{Name:name}
7 }

 

 

那么问题来了,有一天我们发现Student结构体还有一些其他属性。现在的Student是这样的

 

1 type Student struct {
2     Name string
3     Age int
4 }

 

这时我们怎么重构我们的代码?

func NewStudent (name string, age int) *Student 不合适,不向后兼容。

func NewStudentWithAge (name string, age int) *Student 难道以后有新的属性就加N个函数吗,各种属性组合起来?不是很好。

func NewStudent(config *studentConfig) *Student 这个看起来不错,但是也有些问题。不向后兼容,最主要的问题是默认值不好处理。试想一下,Age默认值是5怎么写?

 

这时,函数选项模式是不错的选择。英文名叫做:Functional Options Pattern

type Student struct {
    Name string
    Age int
}

type StudentOption func(*Student)

func WithAge(age int) StudentOption{
    return func(s *Student){
        s.Age = age
    }
}

func NewStudent(name string, options ...StudentOption) *Student{
    student := &Student{Name:name, Age:5}
    for _,o :=range options{
        o(student)
    }
    return student
}

 

调用的时候可以是NewStudent(“zhangsan”),也可以是NewStudent(“lisi”, WithAge(6))。既保持了兼容性,而且1个新属性只需要1个With函数。

各位有没有更好的思路呢?

posted @ 2020-09-29 11:22  JustDotNet  阅读(118)  评论(0编辑  收藏  举报