package main

import "fmt"

/**
 * 构造函数
 * 上班类
 */
type Work struct {
    opts options
}
type options struct {
    startTime string
    lunchTime string
    endTime   string
}

var (
    lunTimeDefault = "中午十二点"
)

type Option func(o *options)

func StartTime(s string) Option {
    return func(opts *options) {
        opts.startTime = s
    }
}

func EndTime(s string) Option {
    return func(opts *options) {
        opts.endTime = s
    }
}

func NewWork(opts ...Option) *Work {
    workOptions := options{}
    for _, opt := range opts {
        opt(&workOptions)
    }
    work := new(Work)
    work.opts = workOptions
    if work.opts.lunchTime == "" {
        work.opts.lunchTime = lunTimeDefault
    }
    return work
}

func main() {
    commonOpts := []Option{
        StartTime("九点半"),
        EndTime("二十点"),
    }

    work := NewWork(commonOpts...)
    fmt.Printf("%+v", work.opts)
}

参考

https://blog.keyboardman.me/2018/01/03/grpc-functional-options-patter/

https://www.jianshu.com/p/0345dea9b63d?utm_campaign=studygolang.com&utm_medium=studygolang.com&utm_source=studygolang.com


Cazy
6 声望2 粉丝