Golang — Factory Method Pattern

Matthias Bruns
3 min readMar 10, 2023

The Factory Method pattern is one of the most commonly used creational patterns in software development. It is part of the famous “Gang of Four” design patterns mentioned in their book “Design Patterns: Elements of Reusable Object-Oriented Software”. In this article, we will discuss how to implement the Factory Method pattern in Golang.

Understanding the Factory Method Pattern

The Factory Method pattern is a creational pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. In simpler terms, it is a way of creating objects without specifying the exact class of object that will be created.

The Factory Method pattern is useful when we want to create objects without knowing their exact class. Instead of creating objects directly, we delegate the creation to a factory that can decide which class of object to create based on certain conditions. This makes our code more flexible and easier to maintain.

Implementing Factory Method Pattern in Golang

In Golang, we can implement the Factory Method pattern using an interface and a struct. The interface will define a method that will be implemented by the struct to create objects. Here is an example:

--

--

Matthias Bruns

Senior Freelancer & Technical Lead Working as a Golang developer since 2020. as a mobile developer since 2013. Focussed on architecture & testability.