The Wayback Machine - https://web.archive.org/web/20240718093547/https://www.geeksforgeeks.org/difference-between-singleton-pattern-and-static-class-in-java/
Open In App

Difference Between Singleton Pattern and Static Class in Java

Last Updated : 21 Feb, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Singleton Pattern belongs to Creational type pattern. As the name suggests, the creational design type deals with object creation mechanisms. Basically, to simplify this, creational pattern explains to us the creation of objects in a manner suitable to a given situation. Singleton design pattern is used when we need to ensure that only one object of a particular class is Instantiated. That single instance created is responsible to coordinate actions across the application.

Different objects trying to invoke an object instantiated as singleton.

If you look at the illustrated diagram above you will see different objects trying to invoke an object instantiated as a singleton. This single instance of the object is responsible to invoke underneath methods or events.

Guidelines for Singleton Pattern are as follows: 

Advantages:

  • Singleton controls concurrent access to the resource.
  • It ensures there is only one object available across the application in a controlled state.

Implementation:

  • Ensure that only one instance of the class exists.
  • Provide global instance to that access by declaring all constructors of the class to be private, providing a static method that returns a reference to the instance, and the instance is stored as a private static variable.

Example

Java




// Java Program to illustrate Difference Between
// Singleton Pattern vs Static Class.
 
// Here illustrating Singleton Pattern
 
// Importing input output classes
import java.io.*;
 
// Class 1
// Helper class
class SingletonEagar {
 
    // Declaration and definition of variable occur
    // simultaneously
    //  Eager initialisation
    private static SingletonEagar instance
        = new SingletonEagar();
 
    // Private constructor of class 1
    private SingletonEagar() {}
 
    public static SingletonEagar getInstance()
    {
        return instance;
    }
}
 
// Class 2
// Helper Class
class Singleton {
 
    // Lazy  declaration and initialisation
    private static Singleton instance;
 
    // Private constructor of Class 2
    private Singleton() {}
 
    public static Singleton getInstance()
    {
 
        // Condition check
        // When instance is null
        // a new object of Singleton class is created
        if (instance == null) {
            instance = new Singleton();
        }
 
        return instance;
    }
}
 
// Class 3
// Helper class
class SingletonSynchronizedMethod {
 
    private static SingletonSynchronizedMethod instance;
 
    // Private constructor of Class 3
    private SingletonSynchronizedMethod() {}
 
    public static synchronized SingletonSynchronizedMethod
    getInstance()
    {
 
        // Condition check
        // When instance is null
        // a new object of Singleton class is created
        if (instance == null) {
            instance = new SingletonSynchronizedMethod();
        }
 
        return instance;
    }
}
 
// Class 4
// Helper class
class SingletonSynchronized {
 
    private static SingletonSynchronized instance;
 
    // Private constructor of Class 4
    private SingletonSynchronized() {}
 
    public static SingletonSynchronized getInstance()
    {
 
        // Again, condition check
        if (instance == null) {
 
            // synchronized block
            synchronized (SingletonSynchronized.class)
            {
 
                if (instance == null) {
                    instance = new SingletonSynchronized();
                }
            }
        }
        return instance;
    }
}
 
// Class 5
// Main class (SingletonExample)
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating instance in main() method of class 1
        SingletonEagar instance1
            = SingletonEagar.getInstance();
 
        // Display message only
        System.out.println(
            instance1
            + " : Singleton Eager initialisation ");
 
        // Creating instance in main() method of class 2
        Singleton instance2 = Singleton.getInstance();
 
        // Display message only
        System.out.println(
            instance2
            + " : Singleton Lazy initialisation ");
 
        // Creating instance in main() method of class 4
        SingletonSynchronized instance3
            = SingletonSynchronized.getInstance();
 
        // Display message only
        System.out.println(instance3
                           + " : Synchronized Singleton");
    }
}


Output

SingletonEagar@2f4d3709 : Singleton Eager initialisation 
Singleton@1d81eb93 : Singleton Lazy initialisation 
SingletonSynchronized@34a245ab : Synchronized Singleton

 

Static Class 

Static nested classes are nested classes that are declared static. In Java, Static classes are a convenient way of grouping classes together. Java doesn’t allow you to create top-level static classes; only nested (inner) classes. That is why a static class is also known as a static inner class or static nested class. 

Guidelines for Static class are as follows:

Advantages:

  • Defining the related or helper classes is possible inside the class by making it static.
  • It can access the private member of the enclosing class through the object reference.
  • The static class provides a nice namespace for the nested class.
  • If the enclosing class gets updated, we are able to update the static class as well at the same location.
  • In JVM, Classloader loads the static class at the time of the first usage only, not when its enclosing class gets loaded.

Implementation: 

  • Static class can only be an inner class or a nested class.
  • Static classes can use any type of access modifier (private, protected, public, or default) like any other static member.
  • Static classes are able to access only the static members of their enclosing class.
  • Static class can interact with the non-static member only through the object of its enclosing class only, as it cannot access the non-static members of its enclosing class directly.

Example 

Java




// Java Program to illustrate Difference Between
// Singleton Pattern vs Static Class.
 
// Here illustrating Static Class
 
// Importing input output classes
import java.io.*;
 
// Class 1
// Helper Class
class GFG_Outer {
 
    // Custom input integer value
    static int x = 20;
 
    public static void display() { System.out.println(x); }
    // Class 2
    // Static inner class
 
    // Can access all static variables of outer class
    // Can't access non-static members
    static class GFG_Inner {
 
        GFG_Inner()
        {
 
            // Display message
            System.out.println(
                "This is Inner Class Constructor...");
 
            // Print the value of x from inside class thrown
            // on console
            System.out.println(
                "Value of \"x\" from inside Inner Class is : "
                + x);
        }
    }
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Printing value of x in the main() method
        System.out.println(GFG_Outer.x);
 
        // Calling display() method from class 1
        GFG_Outer.display();
 
        // static inner class object which is as follows:
        // OuterClass.InnerClass variable = new
        // OuterClass.InnerClass();
        GFG_Outer.GFG_Inner object
            = new GFG_Outer.GFG_Inner();
    }
}


Output

20
20
This is Inner Class Constructor...
Value of "x" from inside Inner Class is : 20

Now we have understood the concepts and working of both of them and have seen conclusive differences in both of them. Now let’s wrap it up by illustrating all differences in a tabular format which is as follows:

Singleton Pattern Static Class
Singleton is a design pattern. Static classes are basically a way of grouping classes together in Java.
Memory is allocated once the object is created. Memory is allocated immediately after any of the class members is accessed.
Singleton implementation can either have static members or instance members. Static classes can contain static members only.
It can implement any other interface or base class is required. It cannot implement the interface or any other base class.
Singleton classes can be used as a method parameter. Static class cannot be used as a method parameter. 
Singleton pattern uses Heap memory. Static classes use stack memory.
It works within the scope of Garbage Collector as it uses Heap memory. Out of scope for Garbage Collector as it uses stack memory.
It supports Dependency Injection (DI) implementation as Singleton follows OOPS concepts. It cannot implement Dependency Injection (DI) as DI is Interface-driven.
Singleton is an architectural pattern and not a language feature. Static is a language feature and not an Architectural pattern.
Disposal of objects is possible. It cannot dispose of the static class as there is no instance created.


Similar Reads

Difference Between Singleton and Factory Design Pattern in Java
Design patterns are essential tools for creating maintainable and scalable software. Two commonly used design patterns in Java are the Singleton and Factory patterns. This article provides an introduction to the Singleton and Factory design patterns with examples. Singleton Design Pattern in JavaThe Singleton pattern is a creational design pattern
3 min read
Difference Between Static and Non Static Nested Class in Java
Nested classes are divided into two categories namely static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes. A class can either be static or non-static in java. So there is a lot of difference between making a class static or non-static. There are two kind
4 min read
Difference between static and non-static method in Java
A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class. Every method in java defaults to a non-static method without static keyword preceding it. Non-static methods can access any static method and static variable, without cr
6 min read
Difference between static and non-static variables in Java
There are three types of variables in Java: Local VariablesInstance VariablesStatic Variables The Local variables and Instance variables are together called Non-Static variables. Hence it can also be said that the Java variables can be divided into 2 categories: Static Variables: When a variable is declared as static, then a single copy of the vari
4 min read
Class Loading and Static Blocks Execution Using Static Modifier in Java
Static is a keyword which when attached to the method, variable, Block makes it Class method, class variable, and class Block. You can call a static variable/method using ClassName. JVM executes the static block at “CLASS LOADING TIME” Execution Order: There is an order in which static block/method/variable gets initialized. Static BlockStatic Vari
3 min read
Singleton Method Design Pattern in Java
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 inst
8 min read
Java Singleton Design Pattern Practices with Examples
In previous articles, we discussed about singleton design pattern and singleton class implementation in detail. In this article, we will see how we can create singleton classes. After reading this article you will be able to create your singleton class according to your requirement, which is simple and without bottlenecks. There are many ways this
6 min read
Difference between Static-1 and Static-0 hazard
Static hazard occur in combinational circuits and can be eliminated by using redundant gates. Static hazard is classified as: 1. Static-1 hazard : If the output is currently at logic state 1 and after the input changes its state, at the same moment the output changes to 0 before settling on 1, then it is a Static-1 hazard. 2. Static-0 hazard : If t
1 min read
How to prevent Singleton Pattern from Reflection, Serialization and Cloning?
Prerequisite: Singleton Pattern In this article, we will see what various concepts can break the singleton property of a class and how to avoid them. There are mainly 3 concepts that can break the singleton property of a class. Let's discuss them one by one. Reflection: Reflection can be caused to destroy singleton property of the singleton class,
6 min read
Understanding storage of static methods and static variables in Java
In every programming language, memory is a vital resource and is also scarce in nature. Hence it’s essential that the memory is managed thoroughly without any leaks. Allocation and deallocation of memory is a critical task and requires a lot of care and consideration. In this article, we will understand the storage of static methods and static vari
4 min read
Practice Tags :
three90RightbarBannerImg