JAVA - Designer Pattern [Singleton]

A design pattern is known as a well-proven solution to a commonly occurring problem in the software design. They can speed up the development process by providing the tested and proven development paradigms. Using design patterns offer few advantages such as:

  • Reusable in multiple projects
  • Provide solutions for an effective system architecture
  • Provide clarity and transparency to the application design
  • Provide robust and highly maintainable code for easy understanding and debug

Java has several design patterns and the Singleton Pattern is the most commonly used.

This design pattern ensures that only one instance of a given class is created and a global access to that instance is provided

Java Singleton Pattern

To implement the Singleton design pattern in the Java programming language, developers need to have the following:

  • Static Member: It will create a single instance in the JVM memory as static are class level variables.
  • Private Constructor: It will restrict the instantiation of the Singleton class from the outside world (i.e. Initialization of this class using the new keyword is prevented)
  • Static factory method: This provides the global point of access to the Singleton object and returns the instance to the caller

In the Java programming language, there are different implementations of the singleton pattern. But before we start, the singleton design pattern should be considered only if all the three criteria’s are satisfied i.e.

  • Ownership of the single instance cannot be changed
  • Lazy initialization is recommended
  • Global access to the singleton instance is not otherwise provided
public class SingletonClassDemo {

    // Static attribute.
    private static SingletonClassDemo instance = null;

    // Private constructor.
    private SingletonClassDemo() {

    }

    // Static function.
    public static SingletonClassDemo getInstance() {
        // If there is no instance available, create new one (i.e. lazy initialization).
        if (instance == null) {
            instance = new SingletonClassDemo();
        }
        return instance;
    }
}

In the preceding example, we wrote a class with a method that creates a new instance of the class if one does not exist. Do note:

  • The instance attribute in the class is defined private and static
  • The constructor of the class is made private so that there is no other way to instantiate the class
  • The accessor function for obtaining the reference to the singleton object is defined public and static

Using singleton pattern helps you to better manage your resources as well as your application design.
In our next post we will discuss about best practices.

Source: JavaCode Geeks