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/
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。