by Dinesh Thakur Category: Classes

Singleton Class in Java: A given class whose object (an instance of the class) is instantiated only once in JVM (Java Virtual Machine) and that only global instance of an object of the class used for every access. Such objects are mainly immutable.

We have to declare a method as static that creates a new instance and returns for the first call and returns the same instance for the next calls.  In practice, Singleton is a design pattern which used when a single state has to maintain throughout the application life-cycle.

In java, the Singleton used in logging, caches, thread pools, configuration settings, device driver objects. Singleton Class should be a static class that allows static and final variable which holds the instance of the Singleton class.

Moreover, also there is a method to provide access to this instance for the other classes.

Some basics rules required to design & implement a singleton class

• We have to declare a private constructor, so there is no way to instantiate the class from the outside.
• We have to declare a private static variable of the class.
• We have to declare a static method to return the instance.

Singleton Class in Java could realize in one of the four following ways :

• Early Loading
• Lazy Loading
• Lazy Loading
• Enum type

Advantage of the singleton class

• Singleton class saves much memory because the object instantiated only once.
• Provide a single point for every access to the object (an instance of the class).
• It allows multiple instances in the future without affecting a singleton class's clients.

Disadvantages of a singleton class

Singleton, one of the most popular design patterns has a lot of serious drawbacks.

• Singleton principle can be violated by many techniques, like cloning.
• Making singleton, a thread-safe also heard.
• Singleton does not support inheritance of the class.
• Singleton does not support distributed environment.

Normal class vs. Singleton class: The instantiation difference between normal and singleton class is that For a normal class we use constructor, whereas for singleton class we use getInstance() method.

Difference between static class and singleton pattern

• Singleton class objects are stored in Heap, whereas static objects stored in the stack.
• The singleton object can cloneable, while we can't clone the static class object.
• The Singleton follow the OOP concepts; static classes don't follow the OOP concepts.
• The Singleton class create only one instance of the object and reuse it whereas a static class cannot create the instance.

Implementing Singleton class with getInstance() method

// Java program implementing Singleton class
// with getInstance() method
class Singleton {
        // static variable one_instance of type Singleton
           private static Singleton one_instance = null;
        // variable of type Message
           public String Message;
       // private constructor restricted to this class itself
           private Singleton() {
              Message = "Singleton, one of the most famous design patterns";
           }
      // static method to create instance of Singleton class
           public static Singleton getInstance() {
                if (one_instance == null)
                   one_instance = new Singleton();
                return one_instance;
           }
}
// Driver Class
public class patterns {
         public static void main(String args[]) {
              // instantiating Singleton class with variable First Call
            Singleton First = Singleton.getInstance();
             // instantiating Singleton class with variable Second Call
            Singleton Second = Singleton.getInstance();
            // instantiating Singleton class with variable Third Call
            Singleton Third = Singleton.getInstance();
            // changing variable of instance First Call
            First.Message = (First.Message).toUpperCase();
               System.out.println("First Call " + First.Message);
               System.out.println("Second Call " + Second.Message);
               System.out.println("Third Call " + Third.Message);
               System.out.println("\n");
           // changing variable of instance Third Call
             Third.Message = (Third.Message).toLowerCase();
               System.out.println("First Call " + First.Message);
               System.out.println("Second Call " + Second.Message);
               System.out.println("Third Call " + Third.Message);
         }
}

Explanation: In the above Singleton class design patterns, when you first call getInstance() method, the above code creates an object of the Singleton class with name one_instance and return to the variable. Since one_instance is static, it changed from null to some object. On next call getInstance() method, since one_instance is not null, it is returned a variable value, instead of instantiating the Singleton class again. This part is done by if condition.

In the patterns class, we instantiate the singleton class with 3 objects First call, Second Call, the Third Call by calling static method getInstance(). However, actually, after the creation of object First call, variables Second Call and Third Call are pointed to object the First call. Hence, if we change the variables of object First call, that is reflected when we access the variables of objects Second Call and Third Call. Also if we change the variables of Third object Call, that is reflected when we access the variables of objects First call and Second Call.





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles