The factory method pattern in Go
This is a continuation of the common design patterns I found in my old code series, which I started in a previous post.
Another common pattern I found is the factory method pattern, which is a design pattern used to create different types of objects using the same interface.
This pattern is actually pretty common in Go. Some good example of this are the builtin I/O libraries:
os.Open() implement the
io.Reader interface which comes in handy for the
parseCsv() method above as we can use it to parse data from multiple sources.
Another scenario when using this design pattern is useful are in unit tests:
By making an interface for
MyObj, we can mock the behaviour of the object in unit tests. You’ll probably find this pattern a lot in open source libraries (e.g periph.io) that provide some sort of testing utils.
Another common occurrence of this pattern are factory functions which are useful when you need to create objects with some defaults:
The above are just a few examples of how the factory design pattern is used in Go, but I hope it’s enough to get an idea of how to use it in practice.
For more design pattern examples, please checkout rolandjitsu/go-design-patterns.
If you find this post helpful, please consider sponsoring.Sponsor