Home » Singleton Pattern In Java: One for All Hero

Singleton Pattern In Java: One for All Hero

by Imran Shaikh
1254 views
Singleton Pattern In Java: One for All Hero

Hey, Tea lovers! Today I will talk about the One for All power. Singleton Design Pattern in Java. This post will be the start of the series on Design Patterns in Java. Singleton pattern is the most basic and easy-to-understand design pattern there is. So it makes a good starting point in the journey of design pattern. Let us jump right into it.

What is Singleton Pattern and Object

By definition, the singleton pattern is a design pattern that restricts the class to initiate only once. Meaning, it can only make only one object of the class. And this pattern is a base pattern of other design patterns as well. Such as Factory Pattern, Builder Pattern, or Prototype Pattern. Don’t worry we will convert them in the upcoming post. So please subscribe to our website.

Now, you would ask, what’s the difference between the SIgnletoin Object and Singleton Pattern? Well, I would say that the SIngleton Pattern is more of an instruction as what we want to achieve, where Singleton Object is the product of that instruction. To make it short, Singleton Pattern to Object is like a blueprint to the product.

For Anime lovers, since it’s only one object for all the users, it’s very much similar to the One for All power in the My Hero Academia 😜.


You can follow me on social media via @coderstea on TwitterLinkedinFacebook, or Instagram. We also share high-quality videos about programming on our Youtube channel. You can also publish your own post on CodersTea.com, just share your thought on Contact Us or let us know in the comments.


Why We need Singleton Pattern

Now you will be wondering why you only need one object of a class, right? Well, there are numerous scenarios where you only want one object of the class. One being the logger object. You only need one, you don’t want to have a new object for every other use.

JDBC pool is a common use. You don’t want to create a new pool for each connection request. If we did, that just destroys the purpose of creating a connection pooling in the first place. More about Connection pooling here. Not only connection but also in thread pooling we use this pattern, which I explained in detail here.

The most obvious example is the Enum in Java. You might know that Enum in Java is nothing but a special class. And one of the specialties is that it’s a Singleton Object. Doesn’t matter from where it gets called, they all get the same Enum. That’s why we generally use the Enum to make sure all of the code gets the same value (object) no matter how many times it gets called.

Now let us see how we can create a singleton object in java.

How to create Singleton Object in Java

Make the constructor private. Yes, that’s it. I am not kidding. Now no one outside of the class can create the object. Of course, we will need at least a single object. Don’t worry, there are other things we have to do in order to create a singleton object. Let’s see.

The first step, like I said, make the constructor private. Just like shown below.

public class SingletonObject {
  // a private constructor
  private SingletonObject(){}
}

Now, how will you create an object? You need at least one, right? to solve that we will use a static function inside the same class. As you know that the private methods or fields are only accessible within the class.

We will leverage that and inside the static function create an object. I will name it as getInstance() as its the most commonly use and a very declarative name. We will also create a static filed in the class to store this new object.

private static SingletonObject singletonObject;

public static SingletonObject getInstance(){
    singletonObject =  new SingletonObject ();
    return singletonObject;
}

Hold on, if we call getInstance() many times it will give us a new object every time. Yes, correct, What we have to do in the getInstance() function, is that we have to check for already existing object. If the object is already there we will return that, if not, we will create a new one, store it and return that. So we will modify the above code like the following.

if(singletonObject != null){
  return singletonObject;
}

And we are done. That’s all it takes to create a singleton object in java. Just to give a full picture, The whole code looks like the following. Now you can add any methods you want inside that class.

I have added a function to demonstrate that only one object is being used. For that, I have defined a static int field count with the initial value of 0. A function named incrementAndGetCount which will increment the count by 1 and return the count value.

public class SingletonObject {
  private static SingletonObject singletonObject;
  private static int count = 0;

  // private constructor
  private SingletonObject(){}

  public static SingletonObject getInstance(){
    // if the object already is already created, we will return that.
    if(singletonObject != null){
      return singletonObject;
    }
    // create a new object as its not created already
    singletonObject =  new SingletonObject ();
    return singletonObject;
  }

// increment count by 1 and return the count
  public int incrementAndGetCount(){
    count += 1;
    return count;
  }
}

Now to test it let’s write the main function.

int testCount = 0;
SingletonObject instance1 = SingletonObject.getInstance();
testCount = instance1.incrementAndGetCount(); // count=1
testCount = instance1.incrementAndGetCount(); // count=2

System.out.println("The testCount should be 2 " + (testCount == 2));

int testCount2 = 0;
// this will return the same object as instance1
SingletonObject instance2 = SingletonObject.getInstance();
testCount2 = instance2.incrementAndGetCount(); // count=3
testCount2 = instance2.incrementAndGetCount(); // count=4

System.out.println("The testCount2 should be 4 " + (testCount2 == 4));

Other Advance Way to Create Singleton Object in Java

One downside of this particular way I showed you is that it’s not thread and reflection safe. There are multiple modifications you have to do in order to fix these issues.

For thread-safe one simple thing you can do is make getInstance() as a synchronized function. Another best option is to utilize Enum.

I will cover them in the next post of Advance Ways to create Singleton Object in java, so please stay connected to Coderstea.com. That’s it for this post.

Conclusion

That’s it for this post. This is the first post from multiple articles about different design patterns in Java that I will be posting soon. The full code for this Singleton Pattern can be found on GitHub. See you in the next post.

HAKUNA MATATA!!!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Privacy & Cookies Policy
0
Would love your thoughts, please comment.x
()
x