美文网首页
Functional Option 2022-05-06

Functional Option 2022-05-06

作者: 9_SooHyun | 来源:发表于2022-05-06 17:36 被阅读0次

Functional Option,工厂模式下的定制化生产
参考https://golang.cafe/blog/golang-functional-options-pattern.html

package main

import "fmt"

type server struct{
    a string
    b string
}

func Build(options ...func(*server)) server {
  svr := server{}
  for _, o := range options {
    o(&svr)
  }
  return svr
}

// 给server.a赋值
func Witha(a string) func(*server) {
  return func(s *server) {
    s.a = a
  }
}
// 给server.b赋值
func Withb(b string) func(*server) {
  return func(s *server) {
    s.b = b
  }
}

func main() {
    s := Build(
        Witha("hhhh"),
        Withb("hehe"),
    )
    fmt.Println(s)
}

例如,golang package github.com/lestrrat-go/file-rotatelogs的工厂方法New就支持了Functional Option

// New creates a new RotateLogs object. A log filename pattern
// must be passed. Optional `Option` parameters may be passed
func New(p string, options ...Option) (*RotateLogs, error)

相关文章

网友评论

      本文标题:Functional Option 2022-05-06

      本文链接:https://www.haomeiwen.com/subject/isjzyrtx.html