函数式选项模式

初始化字段时设置默认值,可以使用函数式选项模式,使用方法如下:

type Option struct {
	A string
	B string
	C int
}

//第一步
func WithA(a string) func(o *Option) {
	return func(o *Option) {
		o.A = a
	}
}

func WithB(b string) func(o *Option)  {
	return func(o *Option) {
		o.B = b
	}
}

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

//第二步
func newOption2(opts ...OptionFunc) (opt *Option) {
	opt = defaultOption
	for _, o := range opts {
		o(opt)
	}
	return
}

//测试
func main() {
	x := newOption("nazha", "小王子", 10)
	fmt.Println(x)
	x = newOption2()
	fmt.Println(x)
	x = newOption2(
		WithA("沙河娜扎"),
		WithC(250),
	)
	fmt.Println(x)
}

  

 

 

参考:Go语言设计模式之函数式选项模式 | 李文周的博客 (liwenzhou.com)

posted @ 2022-06-20 11:02  ☞@_@  阅读(23)  评论(0编辑  收藏  举报