Option 模式

package main

import "fmt"

// Server 是一个结构体,用于表示服务器实例
type Server struct {
	Option
}

// Option 是一个结构体,用于表示服务器选项
type Option struct {
	host string
	port uint16
}

// ServerOption 是一个函数类型,用于设置服务器选项
type ServerOption func(*Server)

// WithHost 返回一个 ServerOption 函数,用于设置服务器主机名
func WithHost(host string) ServerOption {
	return func(s *Server) {
		s.host = host
	}
}

// WithPort 返回一个 ServerOption 函数,用于设置服务器端口号
func WithPort(port uint16) ServerOption {
	return func(s *Server) {
		s.port = port
	}
}

// NewServer 返回一个 Server 实例,用于构建服务器
func NewServer(opts ...ServerOption) *Server {
	s := &Server{
		Option: Option{
			host: "localhost",
			port: 8080,
		},
	}
	for _, opt := range opts {
		opt(s)
	}
	return s
}

// Address 返回服务器的地址表示
func (s *Server) Address() string {
	return fmt.Sprintf("%s:%d", s.host, s.port)
}

func main() {
	server := NewServer(
		WithHost("localhost"),
		WithPort(8080),
	)
	fmt.Println(server.Address())
}

Builder 模式

package main

import "fmt"

// Server 是一个结构体,用于表示服务器实例
type Server struct {
	Option
}

// Option 是一个结构体,用于表示服务器选项
type Option struct {
	host string
	port uint16
}

// ServerBuilder 是一个结构体,用于构建服务器实例
type ServerBuilder struct {
	option Option
}

func NewServerBuilder() *ServerBuilder {
	return &ServerBuilder{
		option: Option{
			host: "localhost",
			port: 8080,
		},
	}
}

// WithHost 返回一个 ServerBuilder 实例,用于设置服务器主机名
func (s *ServerBuilder) WithHost(host string) *ServerBuilder {
	s.option.host = host
	return s
}

// WithPort 返回一个 ServerBuilder 实例,用于设置服务器端口号
func (s *ServerBuilder) WithPort(port uint16) *ServerBuilder {
	s.option.port = port
	return s
}

// Build 返回一个 Server 实例,用于构建服务器
func (s *ServerBuilder) Build() *Server {
	return &Server{
		Option: s.option,
	}
}

// Address 返回服务器的地址表示
func (s *Server) Address() string {
	return fmt.Sprintf("%s:%d", s.host, s.port)
}

func main() {
	server := NewServerBuilder().
		WithHost("localhost").
		WithPort(8080).
		Build()
	fmt.Println(server.Address())
}