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


    在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函数。

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

  • 相关阅读:
    开源项目
    获取手机剩余空间工具类
    圆形图片
    gridview添加header
    Eclipse中10个最有用的快捷键组合
    那些年不错的Android开源项目(转)
    Android 获取系统或SDCARD剩余空间信息(转)
    android之 Activity跳转出现闪屏
    解决Activity启动黑屏及设置android:windowIsTranslucent不兼容activity切换动画问题
    Android studio 导入工程 出现错误
  • 原文地址:https://www.cnblogs.com/13579net/p/13748737.html
Copyright © 2020-2023  润新知