zoukankan      html  css  js  c++  java
  • 更好的创建构造函数的方式

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

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

  • 相关阅读:
    MySQL select语句中where条件的提取过程
    MySQL特性:ICP,Index Condition Pushdown
    MySQL特性:BKA,Batched Key Access,批量索引访问
    MySQL特性:MRR,Multi-Range Read,多范围读
    show engine innodb status 输出结果解读
    IPv6的一点使用小计
    MySQL 通过ibd恢复数据
    explain 小结
    clickhouse的多路径存储策略
    cenos6.5升级glibc2.18
  • 原文地址:https://www.cnblogs.com/13579net/p/13748737.html
Copyright © 2011-2022 走看看