Functional options tạo API khởi tạo object linh hoạt, dễ mở rộng mà không break code cũ.
go
type Server struct {
port int
timeout time.Duration
maxConn int
}
// Option là function type
type Option func(*Server)
// Helper functions trả về Option
func WithPort(p int) Option {
return func(s *Server) { s.port = p }
}
func WithTimeout(d time.Duration) Option {
return func(s *Server) { s.timeout = d }
}
func WithMaxConn(n int) Option {
return func(s *Server) { s.maxConn = n }
}
// Constructor apply options
func NewServer(opts ...Option) *Server {
s := &Server{port: 8080, timeout: 30 * time.Second, maxConn: 100} // defaults
for _, opt := range opts {
opt(s)
}
return s
}
// Sử dụng — chỉ cần truyền options quan tâm
srv := NewServer(
WithPort(9090),
WithTimeout(60 * time.Second),
)