hfSic

hfSic

作成型パターン

ビルダー パターン(Builder Pattern)#

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 Pattern)#

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"))
}
読み込み中...
文章は、創作者によって署名され、ブロックチェーンに安全に保存されています。