builder 模式(構建器模式)#
創建一個 builder 對象,使用該對象方法設置屬性,通過
Build()
方法返回對象使用場景:屬性配置
type ServerBuilder struct {
Server
}
func (s *ServerBuilder) Default(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) Build() Server{
return s.Server
}
# 調用
func main() {
s := ServerBuilder{}
server := s.Default().
WithProtocol("udp").
Build()
}
Functional Options(函數式選項模式)#
創建一個
func
類型,該類型將值賦給接受者,通過新建方法循環入參中的func
切片實現獲取目標對象使用場景:屬性配置
vs 構建器模式:不需要聲明空對象
type Option func(*Server)
func WithProtocal(protocal string) Option {
return func(s *Server) {
s.Protocal = protocal
}
}
func WithProtocal(protocal string) Option {
return func(s *Server) {
s.Protocal = protocal
}
}
func NewServer(addr string,port int,opts ...Option) {
srv := Server{
Addr: addr,
Port: port,
}
for i := range opts {
option(&srv)
}
}
func main() {
s:= NewServer("localhost",1024,Protocal("udp"))
}