Factory method design pattern is a unified method to create a composite object/class. Unlike conventional simple class/structure, there might be possibility that the sub-classes require initialization or pre-value allocation. Hence, user is not able to create the class/structure object via the conventional.
The easiest way is to create a "factory" function that produces the class object (product) based on a given configuration parameters. The function will initialize and configure the class object before returning it to the client.
Here is an example in Go, which is commonly used:
package main
import (
"fmt"
)
type Controller struct {
label string
models *[]byte
views *[]byte
data *[]byte
}
// Factory Method
func newController(name string) *Controller {
return &Controller{
label: name,
models: &[]byte{},
views: &[]byte{},
data: &[]byte{},
}
}
func (c *Controller) Model() {
for i, char := c.models {
fmt.Printf("Model %v: %v\n", i, char)
}
}
func (c *Controller) Name() string {
return c.label
}
func main() {
c := newController("me")
fmt.Printf("%v\n", c.Name())
}
Notice that Controller
needs the factory method newController
in order to initialize all its internal elements. Normal user cannot perform those initialization if he/she is using the conventional way to create the struct ( Controller{}
). Without these initialization, function like Model()
can reach to system panics which is undesirable.