目录

Go 编程模式:Functional Options

目录

函数式选项(functional options)模式

代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package functional_options

import (
  "crypto/tls"
  "fmt"
  "testing"
  "time"
)

type Server struct {
  Addr     string
  Port     int
  Protocol string
  Timeout  time.Duration
  MaxConns int
  TLS      *tls.Config
}

type Option func(*Server)

func Protocol(p string) Option {
  return func(s *Server) {
    s.Protocol = p
  }
}
func Timeout(timeout time.Duration) Option {
  return func(s *Server) {
    s.Timeout = timeout
  }
}
func MaxConns(maxConns int) Option {
  return func(s *Server) {
    s.MaxConns = maxConns
  }
}
func TLS(tls *tls.Config) Option {
  return func(s *Server) {
    s.TLS = tls
  }
}

func NewServer(addr string, port int, options ...func(*Server)) (*Server, error) {
  srv := Server{
    Addr:     addr,
    Port:     port,
    Protocol: "tcp",
    Timeout:  30 * time.Second,
    MaxConns: 1000,
    TLS:      nil,
  }
  for _, option := range options {
    option(&srv)
  }
  //...
  return &srv, nil
}

func TestEx(t *testing.T) {
  s1, _ := NewServer("localhost", 1024)
  s2, _ := NewServer("localhost", 2048, Protocol("udp"))
  s3, _ := NewServer("0.0.0.0", 8080, Timeout(300*time.Second), MaxConns(1000))

  fmt.Printf("%+v \n", s1)
  fmt.Printf("%+v \n", s2)
  fmt.Printf("%+v \n", s3)
}

参考

https://time.geekbang.org/column/article/330212

https://zhuanlan.zhihu.com/p/436468481