Factory Design Pattern on Golang
The Factory design pattern provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. This pattern is useful when you want to delegate the responsibility of object creation to a separate factory class.
Golang Basic Implementation
In Go, we implement the Factory Pattern using functions that return instances of structs (objects).
Unlike object-oriented languages with classes, Go uses struct types and interfaces.
package main
import "fmt"
// Shape interface
type Shape interface {
Draw()
}
// Circle struct
type Circle struct{}
// Draw method for Circle
func (c Circle) Draw() {
fmt.Println("Drawing Circle")
}
// Square struct
type Square struct{}
// Draw method for Square
func (s Square) Draw() {
fmt.Println("Drawing Square")
}
// ShapeFactory function
func ShapeFactory(shapeType string) Shape {
switch shapeType {
case "circle":
return Circle{}
case "square":
return Square{}
default:
return nil
}
}
func main() {
circle := ShapeFactory("circle")
square := ShapeFactory("square")
circle.Draw()
square.Draw()
}
In this example, we define a Shape
interface with a Draw
method. We then create two concrete types, Circle
and Square
, that implement the Shape
interface. The ShapeFactory
function takes a shapeType
parameter and returns an object that implements the Shape
interface based on the input.
When we call ShapeFactory("circle")
, it returns a Circle
object, and when we call ShapeFactory("square")
, it returns a Square
object. We can then call the Draw
method on these objects to draw the respective shapes.
This allows us to create different types of shapes without exposing the concrete implementation details to the client code. The client code only needs to know about the Shape
interface and the ShapeFactory
function, making the code more flexible and maintainable.