Builder Pattern#
Create a builder object, use the object's methods to set properties, and return the object through the
Build()
method.Use case: Property configuration
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
}
# Invocation
func main() {
s := ServerBuilder{}
server := s.Default().
WithProtocol("udp").
Build()
}
Functional Options#
Create a
func
type that assigns values to the receiver, and obtain the target object by looping through thefunc
slice in the new method.Use case: Property configuration
vs Builder Pattern: No need to declare an empty object
type Option func(*Server)
func WithProtocol(protocol string) Option {
return func(s *Server) {
s.Protocol = protocol
}
}
func NewServer(addr string, port int, opts ...Option) {
srv := Server{
Addr: addr,
Port: port,
}
for i := range opts {
opts[i](&srv)
}
}
func main() {
s := NewServer("localhost", 1024, WithProtocol("udp"))
}