Design Patterns : Singleton Design Pattern

Design Patterns : Singleton Design Pattern

Singleton Design pattern is so cool !!

let me start with what and why, I mean what are these patterns and why do we need them? Usually, in software development, there is a constant strive to develop the software in a way that executes fast, has less memory consumption and is scalable at the same time. So there can be many challenges achieving the above three, but every challenge has a pattern and it becomes easy if there exists a standard approach which can tackle the challenge that comes under a similar pattern.

Coming to who introduced these design patterns, In 1994 on 21st October there released a book called "Design Patterns: Elements of Reusable Object-Oriented Software" by Gang of Four. Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.

Enough of facts let's us jump into my experience on how I met the Singleton Design pattern.

So i was working on a backend part of a project where I need to have a database object in order to interact with the database (db) I was pretty clear with the requirement that I need db object in order to run a select query or update query on Database.

So the arguments for the DataBase constructor was the same at all time and I used to copy and paste the object creation code for every single transaction.

later I realized why I didn't create a single object of db and use it all over my code base. by this, I was on the path towards a singleton design pattern.

That's not the end, being a good developer you need to also restrict the code to create multiple objects.

That's exactly what the singleton design pattern is all about.

It says: How efficiently we can restrict the code to create only one object throughout the code.

My first approach: make the constructor private and create a static method which can return the object.

class DataBase{
    DataBase db;
    private DataBase(){
    }
    public static getDataBaseObj(){
        if(db==null){
            db = new Database();
            return db;    
        }
        return db;
    }
}

The code above looks pretty cool, I thought I solved the issue, but actually I didn't. This code can get broken in a multi-thread environment.

So I started using locks in my code. but locks can increase the execution time of threads so I have just used locks in a critical part of the code based on a if condition. The below code is just a pseudo-code

class DataBase{
    static DataBase db;
    private DataBase(){
    }
    public static getDataBaseObj(){  
        if(db==null){
            lock:
                db = new Database();
                return db; 
            unlock: 
        } 
        return db;
    }
}

But there is a catch in this is code as well.

what if the thread t1 executes the if condition line and gives control to t2 and t2 also executes the if condition line then both t1 and t2 enter the if scope end up taking the lock and creating two objects one after the other.

So by searching a lot on internet, i came across this optimized approach which is the Double check approach.

class DataBase{
    static DataBase db;
    private DataBase(){
    }
    public static getDataBaseObj(){  
        if(db==null){
            lock:
                if(db==null){
                    db = new Database();
                    return db;
                }
                else{   
                    unlock:
                } 
        }     
        return db;
    }
}

this way I could efficiently restrict multiple object creation in my code base and got to know about this beautiful design pattern. This was just my scenario but single object requirements could be in many parts of the project where the arguments for creating an object wouldn't change at any time. If they change you can go ahead with creating multiple objects accordingly. And this kind of design pattern comes under the Creational Design pattern.

Let us discuss more about my experience with other design patterns, in forthcoming articles, till then keep learning and enjoy programming...! Bye.