Singleton Pattern in Golang

How to implement singleton design pattern in golang#

Today we will disucss about singleton design pattern and how to implement that in golang.

You have already heard of singleton design pattern because it is very famous and almost every project needed that.

Singleton means single instance. Suppose you want to access database and for the you created a Connection Class which will hold the db connection. if your db connecion class object gets created on every call then there will be too many connection open. which is not good at some point you will get too many connection error from database. here comes the need of singleton, every time we try to create new object it should check if object already created then return the same else create new object and return that.

We do create singleton in OOPs languages using static keyword which stores only one in memory but in terms of golang there is not static keyword available so how we can create singleton.

It is very easy in go we can use package level global variable. look at the following code. it will create a single instance of database connection.

package database

import (
	"database/sql"
	"fmt"
)

type dbConn struct {
	Conn *sql.DB
}

var db *dbConn

func New() *dbConn {
	if db == nil {
		connStrnig := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s",
			"user", "password",
			"localhost", "3306", "db_name")
		// fmt.Println(connStrnig)
		conn, err := sql.Open("mysql", connStrnig)
		if err != nil {
			panic(err)
		}
		return &dbConn{Conn: conn}
	}
	return db
}

after this we can access database connection anywere in our application by simply calling below code.


func getAllUsers() {
    db := database.New()
    rows, err := db.Conn.Query("Select firstname, lastname from users;")
    if err != nil {
        fmt.Println(err)
    }
    defer rows.Close()

    var firstname, lastname string
    for rows.Next() {
        rows.Scan(&firstname,&lastname)
        fmt.Println(firstname, lastname)

    }

}

As you can see how it is easy to implement singleton in golang. there is ton of design patterns we can implement in golang. it is little different than object oriented programming but we can definitely do in idomatic way.

comments powered by Disqus