一、简介
options 与 build 设计模式是用于灵活创建结构体,并给结构体参数赋值。
二、使用教程
2.1 options 模式
type options struct {
Endpoint string
Username string
Password string
Timeout int64
}
type Option func(*options)
func WithEndpoint(endpoint string) Option {
return func(o *options) {
o.Endpoint = endpoint
}
}
func WithUsername(username string) Option {
return func(o *options) {
o.Username = username
}
}
func WithPassword(password string) Option {
return func(o *options) {
o.Password = password
}
}
func WithTimeout(timeout int64) Option {
return func(o *options) {
o.Timeout = timeout
}
}
func NewOptions(opts ...Option) *options {
o := &options{}
for _, opt := range opts {
opt(o)
}
return o
}
func main() {
newOptions := NewOptions(WithEndpoint("redis.com:6379"), WithTimeout(3000))
fmt.Println(newOptions)
}