首页 专题 文章 代码 归档

【Go】Go设计模式之函数选项模式

1. 前言

何为设计模式?

之前看知乎,看到一篇我觉得很不错的回答:就是为了避免语言的不足,比如,如果语言没有循环,那么就用递归实现循环,这就是设计模式

是不是觉得有点道理??

2. 函数选项模式

之前用ElasticSearch 的第三方库(还是es的官方sdk),反正就有一个是使用了这个模式

这种模式主要用于构造函数

今天看了这篇博客:https://www.liwenzhou.com/posts/Go/functional_options_pattern/

就等理解了一些...


普通构造函数,我们都是指定每个参数的位置,然后构造

比如这样:

type Option struct {
    A string
    B string
    C int
}

func NewOption(a string, b string, c int) *Option {
    return &Option{A: a, B: b, C: c}
}

但是我们如果只需要,设置a,c就能构造出一个实例,如何做?

Java很简单,重载即可!

但是,Go里面不能重载呀~

这就用到了此模式!

3. 具体

package main

import "fmt"

type Option struct {
    A string
    B string
    C int
}


type OptionFunc func(*Option)

func WithA(a string) OptionFunc {
    return func(o *Option) {
        o.A = a
    }
}
func WithB(b string) OptionFunc {
    return func(o *Option) {
        o.B = b
    }
}

func WithC(c int) OptionFunc {
    return func(o *Option) {
        o.C = c
    }
}
func NewOption(opts ...OptionFunc) *Option {

    option := &Option{}

    for _, o := range opts {
        o(option)
    }
    return option
}

func main() {
    option := NewOption(
        WithA("你好"),
        WithB("俩"),
        WithC(12),
    )

    fmt.Printf("%#v\n", option)

}

我们在构造函数里面的传入的是可变参数

每一个参数都是一个函数

type OptionFunc func(*Option)

我们想要什么参数,就构造一个此类型的函数即可!

func WithA(a string) OptionFunc {
    return func(o *Option) {
        o.A = a
    }
}
func WithB(b string) OptionFunc {
    return func(o *Option) {
        o.B = b
    }
}

func WithC(c int) OptionFunc {
    return func(o *Option) {
        o.C = c
    }
}

因为go语言有指针,所以把指针传入进去,原来的其他的值还在!

此文阅读完毕,您可以:分享
二维码图片 扫描关注我们哟