选项模式
package main
import (
"time"
)
type Connection struct {
addr string
cache bool
timeout time.Duration
}
const (
defaultTimeout = 10
defaultCaching = false
)
type options struct {
timeout time.Duration
caching bool
}
// Option overrides behavior of Connect.
//type Option interface {
// apply(*options)
//}
type optionFunc func(*options)
//func (f optionFunc) apply(o *options) {
// f(o)
//}
type optionFuncs []optionFunc
func (o optionFuncs) Apply(u *options) {
for _, f := range o {
f(u)
}
}
func WithTimeout(t time.Duration) optionFunc {
return optionFunc(func(o *options) {
o.timeout = t
})
}
func WithCaching(cache bool) optionFunc {
return optionFunc(func(o *options) {
o.caching = cache
})
}
// Connect creates a connection.
func NewConnect(addr string, opts ...optionFunc) (*Connection, error) {
options := options{
timeout: defaultTimeout,
caching: defaultCaching,
}
optionFuncs(opts).Apply(&options)
return &Connection{
addr: addr,
cache: options.caching,
timeout: options.timeout,
}, nil
}
最后更新于