The Factory Pattern defines a Creator (factory) that returns Products through a common interface, with multiple Concrete Products created inside the Factory Method, so the Client never needs to know which implementation it receives.
Problem it solves:
“How do I create objects without tightly coupling code to specific types?”
Why it's needed:
Example:
package main
import "errors"
type Database interface {
Connect() error
}
func NewDatabase(db string) (Database, error) {
switch db {
case "postgresql":
return &Postgres{}, nil
case "mysql":
return &MySQL{}, nil
case "mongoDB":
return &MongoDB{}, nil
default:
return nil, errors.New("database not supported")
}
}
type Postgres struct{}
func (p *Postgres) Connect() error { return nil }
type MySQL struct{}
func (m *MySQL) Connect() error { return nil }
type MongoDB struct{}
func (m *MongoDB) Connect() error { return nil }
func main() {
postgres, _ := NewDatabase("postgresql")
mysql, _ := NewDatabase("mysql")
mongo, _ := NewDatabase("mongoDB")
_ = postgres.Connect()
_ = mysql.Connect()
_ = mongo.Connect()
}
https://en.wikipedia.org/wiki/Factory_method_pattern
In the Builder Pattern: the Product is the object being built, the Builder defines abstract construction steps, the Concrete Builder implements those steps and assembles the product, and the Director controls the order of steps. The Build() method returns the final constructed object.