Go 设计模式-函数选项模式


简介

在 Go 语言中,函数选项模式(Options Pattern)是一种常用的设计模式,它可以让我们在创建对象时更灵活地设置选项,避免了使用多个构造函数或者传递大量参数的问题。本文将通过一个具体的示例,详细说明如何在 Go 中实现函数选项模式。

示例

丝滑小连招

package main

import "fmt"

type Option func(*Param)

type Param struct {
	A string
	B int
	C bool
}

func WithA(a string) Option {
	return func(o *Param) {
		o.A = a
	}
}

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

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

func NewParam(opts ...Option) Param {
	opt := Param{
		A: "default",
		B: 100,
		C: true,
	}

	for _, o := range opts {
		o(&opt)
	}

	return opt
}

func main() {
	opt1 := NewParam()
	fmt.Printf("Default: %v\n", opt1)

	opt2 := NewParam(
		WithA("hello"),
		WithB(200),
		WithC(false),
	)
	fmt.Printf("Custom: %v\n", opt2)
}


如果本文帮助到了你,帮我点个广告可以咩(o′┏▽┓`o)


文章作者: Anubis
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Anubis !
评论
  目录