go build模式 与 option模式

go的 build 模式 与 option模式

type Server struct {
    Addr     string
    Port     int
    Protocol string
    Timeout  time.Duration
    MaxConns int
    TLS      *tls.Config
}
// 针对于上述这样的配置,我们需要有多种不同的创建不同配置 Server 的函数
func NewDefaultServer(addr string, port int) (*Server, error) {
  return &Server{addr, port, "tcp", 30 * time.Second, 100, nil}, nil
}
func NewTLSServer(addr string, port int, tls *tls.Config) (*Server, error) {
  return &Server{addr, port, "tcp", 30 * time.Second, 100, tls}, nil
}
func NewServerWithTimeout(addr string, port int, timeout time.Duration) (*Server, error) {
  return &Server{addr, port, "tcp", timeout, 100, nil}, nil
}
func NewTLSServerWithMaxConnAndTimeout(addr string, port int, maxconns int, timeout time.Duration, tls *tls.Config) (*Server, error) {
  return &Server{addr, port, "tcp", 30 * time.Second, maxconns, tls}, nil
}
// 针对上述代码,改进为build模式
//使用一个builder类来做包装
type ServerBuilder struct {
  Server
}
func (s *ServerBuilder) Create(addr string, port int) *ServerBuilder {
  s.Server.Addr = addr
  s.Server.Port = port
  //其它代码设置其它成员的默认值
  return s
}
func (s *ServerBuilder) WithProtocol(protocol string) *ServerBuilder {
  s.Server.Protocol = protocol 
  return s
}
func (s *ServerBuilder) WithMaxConn( maxconn int) *ServerBuilder {
  s.Server.MaxConns = maxconn
  return s
}
func (s *ServerBuilder) WithTimeOut( timeout time.Duration) *ServerBuilder {
  s.Server.Timeout = timeout
  return s
}
func (s *ServerBuilder) WithTLS( tls *tls.Config) *ServerBuilder {
  s.Server.TLS = tls
  return s
}
func (s *ServerBuilder) Build() (Server) {
  return  s.Server
}
s := ServerBuilder{}
server, err := s.Create("127.0.0.1", 8080).
  WithProtocol("udp").
  WithMaxConn(1024).
  WithTimeOut(30*time.Second).
  Build()
// 针对build模式,改为option模式
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,
  }
  for _, option := range options {
    option(&srv)
  }
  return &srv, nil
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值