Go — Singleton Pattern

Haluan Mohammad Irsad
2 min readDec 22, 2018

Prerequisite

Before read this article, make sure you have a good understanding towards Go Interface.

Introduction

Singleton Pattern is the most known design pattern, this pattern can help you to create object and reused it for the whole lifetime of your system.

This pattern designed to make sure that only single object created, and provide solution on how to access the object without do multiple instantiation every time the object is called.

Build Once Time for the Lifetime

Uncle Martin is a successful engines distributor in the town. He has a big warehouse. The operational in the factory mainly is put in the goods, release the engines out to customer, and check the current capacity of the warehouse.

In this case, every operational is conducted, the warehouse doesn’t have to be rebuild again right? Uncle Martin only need to build the warehouse once time for the lifetime.

At this case, the warehouse can be treated as the singleton object. We can write the abstraction for this case, like below:

  1. Write the Warehouse abstraction, we put all the operation of the Uncle Martin operations inside the interface

2. Create the implementor

As you can see above, the var instance *warehouseImpl used as the holder of the state of the Warehouse instance. GetInstance() used to check whether the instance is been instantiate or not. If the instance is nill, then automatically will be instantiate new one.

3. As usual, we will crate the wrapper for all of the interface methods

You can inspect the code above, there is no instantiation code to call WarehouseImpl .We delegate the object lifecycle to GetInstance() method.

4. The last one, is main.go to execute the whole operations

As you can see above, we don’t have to pass any object or instantiate the struct to the “operator” methods.

Singleton design pattern, works like the real warehouse of Uncle Martin, build once time for the lifetime!

Conclusion

Based on our experience above, singleton pattern can be useful for continuous changes inside the object, and shared state-value across boundary of the system. Because the shared value requirement, thus we have to ensure that the struct only has one instance.

With singleton pattern, the creational and the object lifecycle can be managed in isolated location, and avoiding leaked to another domain. If creational and lifecycle management leaked to other domain, that will causing inconsistent value across the boundary.

Extra Notes: Gopher is Go Language mascot (used as part of the image cover in this article), created by Renee French. Creative Commons Attribution 3.0 licensed.

--

--