ビルダー パターン#
ビルダー オブジェクトを作成し、そのオブジェクトのメソッドを使用して属性を設定し、
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()
}
関数型オプション パターン#
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"))
}