Go 设计模式
Functional Options 模式、Pipeline 模式、Fan-out/Fan-in、对象池
Go 设计模式
Go 的设计模式自有特色——Functional Options 替代构造函数重载、Pipeline 处理数据流、对象池复用资源。
学完本章你将: 掌握 Functional Options、Pipeline、Fan-out/Fan-in、对象池。
Functional Options 模式
go
type Server struct {
host string
port int
timeout time.Duration
}
type Option func(*Server)
func WithHost(h string) Option { return func(s *Server) { s.host = h } }
func WithPort(p int) Option { return func(s *Server) { s.port = p } }
func WithTimeout(t time.Duration) Option { return func(s *Server) { s.timeout = t } }
func NewServer(opts ...Option) *Server {
s := &Server{host: "localhost", port: 8080, timeout: 30 * time.Second}
for _, opt := range opts { opt(s) }
return s
}
srv := NewServer(WithPort(9000), WithTimeout(10*time.Second))
Pipeline 模式
go
func generator(nums ...int) <-chan int {
out := make(chan int)
go func() { for _, n := range nums { out <- n }; close(out) }()
return out
}
func square(in <-chan int) <-chan int {
out := make(chan int)
go func() { for n := range in { out <- n * n }; close(out) }()
return out
}
// 管道串联
c := generator(1, 2, 3, 4, 5)
out := square(c)
for n := range out { fmt.Println(n) }
sync.Pool —— 对象池
go
var bufPool = sync.Pool{
New: func() any { return new(bytes.Buffer) },
}
func process(data string) {
buf := bufPool.Get().(*bytes.Buffer)
defer bufPool.Put(buf) // 用完后归还
buf.Reset()
buf.WriteString(data)
// ...
}