Factory Method
Explore the concept of factory methods in Go to create structs efficiently without traditional constructors. Understand how to enforce factory usage through visibility rules and the practical differences between new and make functions for structs and maps. This lesson helps you write safer, cleaner initialization code in Go.
We'll cover the following...
A factory of structs
Go doesn’t support constructors as in OO-languages, but constructor-like factory functions are easy to implement. Often, a factory is defined for the type for convenience. By convention, its name starts with new or New. Suppose we
define a File struct type:
type File struct {
fd int // file descriptor number
name string // filename
}
Then, the factory, which returns a pointer to the struct type, would be:
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
}
return &File{fd, name}
}
Often a Go constructor can be written succinctly using initializers within the factory function. An example of calling it:
f := NewFile(10, "./test.txt")
If File is defined as a struct type, the expressions new(File) and &File{} are equivalent. Compare this with the clumsy initializations in most OO languages:
File f = new File( ...)
In general, we say that the factory instantiates an object of ...