hfSic

hfSic

创建型模式

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"))
}
加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。