Golang Option设置模式
Kubernetes、etcd等开源golang项目中经常见到的设计模式之一,常在给应用启动设置参数中见到:
type Client interface {
Conn()
}
type DBClient struct {
timeout int
retryTimes int
}
func (c DBClient) Conn() {
// Do SOMETHING
}
type ClientConnOption func(*ClientConnOptions)
type ClientConnOptions struct {
retryTimes int
timeout int
}
func WithRetryTimes(retryTimes int) ClientConnOption {
return func(options *ClientConnOptions) {
options.retryTimes = retryTimes
}
}
func WithTimeout(timeout int) ClientConnOption {
return func(options *ClientConnOptions) {
options.timeout = timeout
}
}
var defaultClientOptions = ClientConnOptions{
retryTimes: 3,
timeout: 5,
}
func NewClient(opts ...ClientConnOption) Client {
options := defaultClientOptions
for _, optFunc := range opts {
optFunc(&options)
}
return &DBClient{
timeout: options.timeout,
retryTimes: options.retryTimes,
}
}