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"))
}