Skip to content

Instantly share code, notes, and snippets.

@NewbMiao
Created February 2, 2018 07:39
Show Gist options
  • Save NewbMiao/5f4f0376828f0c487879395538647a13 to your computer and use it in GitHub Desktop.
Save NewbMiao/5f4f0376828f0c487879395538647a13 to your computer and use it in GitHub Desktop.
函数式配置模式
package main
import (
"fmt"
)
var defaultStuffClient = stuffClient{
retries: 3,
timeout: 2,
}
type StuffClientOption func(*stuffClient)
func WithRetries(r int) StuffClientOption {
return func(o *stuffClient) {
o.retries = r
}
}
func WithTimeout(t int) StuffClientOption {
return func(o *stuffClient) {
o.timeout = t
}
}
type StuffClient interface {
DoStuff() error
}
type stuffClient struct {
conn Connection
timeout int
retries int
}
type Connection struct{}
func NewStuffClient(conn Connection, opts ...StuffClientOption) StuffClient {
client := defaultStuffClient
for _, o := range opts {
o(&client)
}
client.conn = conn
return client
}
func (c stuffClient) DoStuff() error {
return nil
}
// The Test
func main() {
x := NewStuffClient(Connection{})
fmt.Println(x) // prints &{{} 2 3}
x = NewStuffClient(Connection{}, WithRetries(1))
fmt.Println(x) // prints &{{} 2 1}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment