NOTE

Abstract Factory Pattern

Abstract-factory notes showing related product families and a Go implementation with engines, wheels, factories, and a client.

Software Architecture & Engineering1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What Is It?

There are multiple products, each with a corresponding factory, and each product is composed of several smaller products. The Abstract Factory pattern creates families of related products.

2. Golang

2.1. Products

/* A car has an engine */
type Engine interface {
	Create()
}

type QQEngine struct {
}

func (Q QQEngine) Create() {
	fmt.Println("create QQ engine")
}

type AodiEngine struct {
}

func (AodiEngine) Create() {
	fmt.Println("create Aodi engine")
}

/* A car has wheels */
type Wheel interface {
	Create()
}

type QQWheel struct {
}

func (Q QQWheel) Create() {
	fmt.Println("create QQ wheel")
}

type AodiWheel struct {
}

func (a AodiWheel) Create() {
	fmt.Println("create Aodi wheel")
}

2.2. Factories

/* Factory for creating cars */
type CarFactory interface {
	CreateEngine() Engine
	CreateWheel() Wheel
}

type QQCarFactory struct {
}

func (Q QQCarFactory) CreateEngine() Engine {
	return &QQEngine{}
}

func (Q QQCarFactory) CreateWheel() Wheel {
	return &QQWheel{}

}

type AodiCarFactory struct {
}

func (a AodiCarFactory) CreateEngine() Engine {
	return &AodiEngine{}
}

func (a AodiCarFactory) CreateWheel() Wheel {
	return &AodiWheel{}

}

2.3. Client

func main() {
	BuildCar(&abstractfactory.QQCarFactory{})
	BuildCar(&abstractfactory.AodiCarFactory{})

}

func BuildCar(factory abstractfactory.CarFactory)  {
	factory.CreateEngine().Create()
	factory.CreateWheel().Create()

}

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub