In golang, we use interfaces to define a contract for a particular type. Factory pattern uses this interface to create instance / object of a particular type like Storage, Service, Document etc.
Implementing Factory pattern
- Define an interface with a method to create the object.
package factory
type Document interface {
Render() string
}
- Create different types which implement the interface.
package factory
type PDF struct {
data string
}
func (p *PDF) Render() string {
return "PDF: " + p.data
}
type Word struct {
data string
}
func (w *Word) Render() string {
return "Word: " + w.data
}
- Create a factory function which returns the object based on some condition.
package factory
func NewDocument(docType string, data string) Document {
switch docType {
case "pdf":
return &PDF{data: data}
case "word":
return &Word{data: data}
default:
return nil
}
}
Example usage
func main() {
pdfDoc := DocumentFactory("pdf")
wordDoc := DocumentFactory("word")
pdfDoc.Render()
wordDoc.Render()
}
This pattern is useful when we have different implementations of similar Interfaces like postgres storage, redis storage etc.. and It also helps to switch between these implementation if they’re interchangable.