golang設計模式之選項模式
阿新 • • 發佈:2020-08-27
type Options struct {
StrOption1 string
StrOption2 string
StrOption3 string
IntOption1 int
IntOption2 int
IntOption3 int
}
type Option func(opts *Options)
func InitOption3(opts ...Option) { options := &Options{} for _, opt := range opts { opt(options) } fmt.Printf("init options3:%#v\n", options) }
func WithStringOption1(str string) Option { return func(opts *Options) { opts.StrOption1 = str } } func WithStringOption2(str string) Option { return func(opts *Options) { opts.StrOption2 = str } } func WithStringOption3(str string) Option { return func(opts *Options) { opts.StrOption3 = str } } func WithIntOption1(val int) Option { return func(opts *Options) { opts.IntOption1 = val } } func WithIntOption2(val int) Option { return func(opts *Options) { opts.IntOption2 = val } } func WithIntOption3(valint) Option { return func(opts *Options) { opts.IntOption3 = val } }
func main() { InitOption3( WithStringOption1("str1"), WithStringOption3("str3"), WithIntOption3(3), WithIntOption2(2), WithIntOption1(1), WithStringOption2("str2"), ) }
執行:
init options3:&main.Options{StrOption1:"str1", StrOption2:"str2", StrOption3:"str3", IntOption1:1, IntOption2:2, IntOption3:3}