Go - options模式(函数式选项模式)

作为 Golang 开发人员,遇到的众多问题之一是试图将函数的参数设为可选。这是一个非常常见的用例,有一些对象应该使用一些基本的默认设置开箱即用,并且您可能偶尔想要提供一些更详细的配置。

在python 中,你可以给参数一个默认值,并在调用方法时省略它们。但是在 Golang 中,是无法这么做。

那么怎么解决这个问题呢? 答案就是Options模式。Options模式在Golang中应用十分广泛,几乎每个框架中都有他的踪迹。

  1. 传统方式:
package main

import "fmt"

type Person struct {
    Name string
    Age int
    Gender int
    Height int

    Country string
    Address string
}


func NewPerson(name string, age, gender, height int, country, address string) *Person{
    return &Person{
        Name: name,
        Age:age,
        Gender:gender,
        Height:height,
        Country:country,
        Address:address,
    }
}

func main()  {
    person := NewPerson("dongxiaojian", 18, 1, 180, "china", "Beijing")
    fmt.Printf("%+v\n", person)
}

可以发现,在这种方式中,拓展起来是非常麻烦的,以及设置出默认值十分繁琐。

  1. options模式

    package main
    
    import "fmt"
    
    type Person struct {
     Name string
     Age int
     Gender int
     Height int
    
     Country string
     City    string
    }
    
    type Options func(*Person)
    
    func WithPersonProperty (name string, age,gender,height int) Options {
     return func(p *Person){
         p.Name = name
         p.Age = age
         p.Gender = gender
         p.Height = height
     }
    }
    
    func WithRegional(country, city string) Options {
     return func(p *Person){
         p.Country = country
         p.City = city
     }
    }
    
    func NewPerson(opt ...Options) *Person{
     p := new(Person)
     p.Country = "china"
     p.City = "beijing"
     for _, o := range opt{
         o(p)
     }
     return p
    }
    
    func main()  {
    
     // 默认值方式
     person := NewPerson(WithPersonProperty("dongxiaojian", 18, 1, 180))
     fmt.Printf("%+v\n", person)
    
     // 设置值
     person2 := NewPerson(WithPersonProperty("dongxiaojian", 18, 1, 180),WithRegional("china", "hebei"))
     fmt.Printf("%+v\n", person2)
    }
    
    
    

    下次可以通过with**函数进行增加属性,以及使用默认值。 这样看起来条理清晰了很多。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第5章 函数和函数式编程 5.1 引言函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。函数...
    VIVAFT阅读 976评论 0 5
  • 长久以来,面向对象在 JavaScript 编程范式中占据着主导地位。不过,最近人们对函数式编程的兴趣正在增长。函...
    神刀阅读 484评论 0 0
  • 一、函数式编程学习前的基础知识 1.1、Array 的常见操作map:映射的意思,它把数据进行循环,每次循环都会走...
    IIronMan阅读 421评论 0 3
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,448评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,891评论 0 23