- read

Factory Design Pattern in Go

Pravand Katyare 15

Factory pattern is used for object creation and one of the most used design pattern.

A closed approached is followed for object creation as it provides a way to hide the logic of how instances are being created.

When To?

This pattern is used when only required information needs to be passed and rest of the details are to be added based on the code template implemented to return the instance.

Scenario

Let’s consider a scenario of hiring an employee into a multi-national company.

struct Employee{ 
Name, Position string
Salary int
Currency string
}

It is taken for granted that an employee will get paid as per company’s standard pay and currency.

So to create an instance we already have some information by default (i.e standard pay and currency) with us and need some information to be entered.

func NewEmployee(_name, _position string) Employee {
return &Employee{
Name: _name,
Position: _position,
Salary: 20000,
Currency: "USD",
}
}

Passing the required value to the function and the rest of the default values will be added be the function itself.

Let’s have a look at the code as whole after including main() function

type Employee struct { 
Name, Position string
Salary int
Currency string
}
func NewEmployee(_name, _position string) *Employee {
return &Employee{
Name: _name,
Position: _position,
Salary: 20000,
Currency: "USD",
}
}
func main() {
emp:= NewEmployee("Foo Bar", "Software Engineer")

fmt.Println("Employee: ", emp)
}

This will return us an instance with all the values

Employee: &{Foo Bar Software Engineer 20000 USD}

Factory pattern is object creation pattern mostly used in the frameworks or third-party libraries which requires object creation for further processing, thus it is widely used.

It can be widely used when the scenarios is to build an SDKs or frameworks which require lots of object creations.

More on the factory pattern in next blog.

Happy Coding…!!!

More Readings: