Singleton Class Flashcards

1
Q

What is a Singleton Class?

A

Java Singleton Class

In object-oriented programming, a java singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Java Singleton classes, the new variable also points to the first instance created. So whatever modifications we do to any variable inside the class through any instance, affects the variable of the single instance created and is visible if we access that variable through any variable of that class type defined.

Remember the key points while defining a class as a singleton class that is while designing a singleton class:

Make a constructor private.

Write a static method that has the return type object of this singleton class. Here, the concept of Lazy initialization is used to write this static method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Purpose of singleton class

A

Purpose of Singleton Class

The primary purpose of a java Singleton class is to restrict the limit of the number of object creations to only one. This often ensures that there is access control to resources, for example, socket or database connection.

Memory space wastage does not occur with the use of the singleton class because it restricts instance creation. As the object creation will take place only once instead of creating it each time a new request is made.

We can use this single object repeatedly as per the requirements. This is the reason why multi-threaded and database applications mostly make use of the Singleton pattern in Java for caching, logging, thread pooling, configuration settings, and much more.

For example, there is a license with us, and we have only one database connection or suppose our JDBC driver does not allow us to do multithreading, then the Singleton class comes into the picture and makes sure that at a time, only a single connection or a single thread can access the connection.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to Design/Create a Singleton Class in Java?

A

To create a singleton class, we must follow the steps, given below:

1.Ensure that only one instance of the class exists.

2.Provide global access to that instance by

Declaring all constructors of the class to be private.

Providing a static method that returns a reference to the instance. The lazy initialization concept is used to write the static methods.

The instance is stored as a private static variable.

Example of singleton classes isRuntime class, Action Servlet, and Service Locator. Private constructors and factory methods are also an example of the singleton class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Forms of Singleton Class Pattern

A

There are two forms of singleton design patterns, which are:

Early Instantiation:The object creation takes place at the load time.

Lazy Instantiation:The object creation is done according to the requirement

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Implementing Singleton Class

A

Implementation:Let us briefly how the singleton class varies from the normal class in java. Here the difference is in terms of instantiation as for normal class we use a constructor, whereas for singleton class we use thegetInstance() methodwhich we will be peeking out in example 1 as depicted below. In general, in order to avoid confusion, we may also use the class name as the method name while defining this method which will be depicted in example 2 below as follows.

Example 1:

Java

// Java program implementing Singleton class

// with using getInstance() method

// Class 1

// Helper class

class Singleton {

// Static variable reference of single_instance

// of type Singleton

private static Singleton single_instance = null;

// Declaring a variable of type String

public String s;

// Constructor

// Here we will be creating private constructor

// restricted to this class itself

private Singleton()

{

s = “Hello I am a string part of Singleton class”;

}

// Static method

// Static method to create instance of Singleton class

public static synchronized Singleton getInstance()

{

if (single_instance == null)

single_instance = new Singleton();

return single_instance;

}

}

OutputHashcode of x is 558638686 Hashcode of y is 558638686 Hashcode of z is 558638686 Three objects point to the same memory location on the heap i.e, to the same object

Output Explanation:



How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

The Singleton Class Summary

A

36% off

Try hands-on Java with Programiz PRO!

Claim Discount Now

Programiz PRO

Java Singleton Class

In Java, Singleton is a design pattern that ensures that a class can only have one object.

To create a singleton class, a class must implement the following properties:

Create aprivateconstructor of the class to restrict object creation outside of the class.

Create aprivateattribute of the class type that refers to the single object.

Create apublic staticmethod that allows us to create and access the object we created. Inside the method, we will create a condition that restricts us from creating more than one object.

Example: Java Singleton Class Syntax

class SingletonExample { // private field that refers to the object private static SingletonExample singleObject; private SingletonExample() { // constructor of the SingletonExample class } public static SingletonExample getInstance() { // write code that allows us to create only one object // access the object as per our need } }

In the above example,

private static SingletonExample singleObject- a reference to the object of the class.

private SingletonExample()- a private constructor that restricts creating objects outside of the class.

public static SingletonExample getInstance()- this method returns the reference to the only object of the class. Since the methodstatic, it can be accessed using the class name.

Use of Singleton in Java

Singletons can be used while working with databases. They can be used to create a connection pool to access the database while reusing the same connection for all the clients. For example,

class Database {

private static Database dbObject;

private Database() { }

public static Database getInstance() {
// create object if it’s not already created

if(dbObject == null) {
dbObject = new Database(); }

// returns the singleton object return dbObject;

}
public void getConnection() {

System.out.println(“You are now connected to the database.”);
}
}
class Main { public static void main(String[] args) {
Database db1;

// refers to the only object of Database db1= Database.getInstance();

db1.getConnection();
}
}

Run Code

When we run the program, the output will be:

You are now connected to the database.

In our above example,

We have created a singleton classDatabase.

ThedbObjectis a class type field. This will refer to the object of the classDatabase.

The private constructorDatabase()prevents object creation outside of the class.

The static class type methodgetInstance()returns the instance of the class to the outside world.

In theMainclass, we have class type variabledb1. We are callinggetInstance()usingdb1to get the only object of theDatabase.

The methodgetConnection()can only be accessed using the object of thr

How well did you know this?
1
Not at all
2
3
4
5
Perfectly