Go does not have built-in Factory, Builder, or Singleton patterns; you implement them manually using functions, structs, and pointers. Use a constructor function for a Factory, a method-chaining struct for a Builder, and a package-level variable with a sync.Once guard for a Singleton.
// Singleton example
var instance *MyType
var once sync.Once
func GetInstance() *MyType {
once.Do(func() {
instance = &MyType{}
})
return instance
}
// Factory example
func NewMyType(config Config) *MyType {
return &MyType{config: config}
}
// Builder example
type MyTypeBuilder struct {
config Config
}
func (b *MyTypeBuilder) SetOpt(opt string) *MyTypeBuilder {
b.config.Opt = opt
return b
}
func (b *MyTypeBuilder) Build() *MyType {
return &MyType{config: b.config}
}