Would You Like To Use a Singleton Class?

In any programming language, A singleton class plays a role to store the data, and get it from everywhere using a getter setter and here are many more ways to use it.

Arnish Gupta
2 min readJul 10, 2020

Singleton means a single object. When we access the singleton class from multiple places then the object is not created multiple times, it will always have a single object.

After complete this article you will get the answers to the below questions:

  • Q1. How can we make a class Singleton?
  • Q2. How can I use a Singleton class?

We can make the class singleton in two steps. Let’s lookup.

Photo by Patrick Selin on Unsplash

I am using Java programming here, we can implement this in any language, the concept is the same only syntax difference. We will have a Test class, see that in below code

public class Test {private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
  • Step 1: Make the constructor private.
private Test(){}
  • Step 2: Make a static variable and static method that return the object of this test class.
## Static variable
private static Test testObj = null;
## Static method
public static Test getInstance() {
if (testObj == null){
testObj = new Test();
}
return testObj;
}

Let’s merge all the code in a Test class:

public class Test {private static Test testObj = null; private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static Test getInstance() {
if (testObj == null){
testObj = new Test();
}
return testObj;
}
}

Now when you want to get an object of a Test class, you can get it using the code Test.getInstance();

public class TestResult {public static void main(String[] args) {
Test obj1 = Test.getInstance();
obj1.setId(23);
Test obj2 = Test.getInstance();
System.out.println("Id: " + obj2.getId());
obj2.setName("Behn");
System.out.println("Name: " + obj1.getName());
}
}
## OutputId: 23
Name: Behn

That’s it. I hope it will help to understand the concept. Clap for me when you happy and share a smile with me also.

Thank you for reading. Have a wonderful day!!

Sign up to discover human stories that deepen your understanding of the world.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Responses (1)

Write a response