函数式选项模式

函数式选项模式

Effective on November 12, 2024·wylu
wylu

YouTube

示例


type OptFunc func(*Opts)

type Opts struct {
	maxConn   int
	id        string
	tls       bool
}

func defaultOpts() Opts {
	return Opts{
		maxConn: 100,
		id:      "default",
		tls:     false,
	}
}

func withTLS(opts *Opts) {
	opts.tls = true
}

func withMaxConn(maxConn int) OptFunc {
	return func(opts *Opts) {
		opts.maxConn = maxConn
	}
}

type Server struct {
	Opts
}

func NewServer(opts ...OptFunc) *Server {
	o := defaultOpts()
	for _, fn := range opts {
		fn(&o)
	}
	return &Server{Opts: o}
}
server := NewServer(withTLS, withMaxConn(10))
最后更新于