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
}