Home Design Pattern Singleton Pattern In Java: One for All Hero

Singleton Pattern In Java: One for All Hero

Published: Last Updated on 4 comments

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. The 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 patterns. 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. This means 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 to what we want to achieve, whereas Singleton Object is the product of that instruction. To make it short, Singleton Pattern to Object is like a blueprint for 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 😜.

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 in the class. One is 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 in connection but also thread pooling we use this pattern, which I explained in detail here.

The most obvious example is 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 where it gets called, they all get the same Enum. That’s why we generally use 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 to create a singleton object. Let’s see.

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

public class SingletonObject {
  // a private constructor
  private SingletonObject(){}
}Code language: PHP (php)

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() it’s the most common use and a very declarative name. We will also create a static file in the class to store this new object.

private static SingletonObject singletonObject;

public static SingletonObject getInstance(){
    singletonObject =  new SingletonObject ();
    return singletonObject;
}Code language: Java (java)

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 objects. 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;
}Code language: JavaScript (javascript)

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 an 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;
  }
}Code language: PHP (php)

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));Code language: JavaScript (javascript)

Other Advance Ways to Create Singleton Objects 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 to fix these issues.

For thread-safe one simple thing you can do is make getInstance() 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. 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!!!


I would be happy to connect with you guys on social media. It’s @coderstea on TwitterLinkedinFacebook, Instagram, and YouTube.

Please Subscribe to the newsletter to know about the latest posts from CodersTea.


Subscribe
Notify of
guest
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ads
Ads
Ads

@2023 All Right Reserved. Designed and Developed by CodersTea

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