Java design pattern Singleton

Today we will take a look at the first Java design pattern from the category of patterns intended for creating objects (creational patterns) – Singleton.

Read more about other design patterns:

What is the Singleton Java design pattern?

Singleton is a design pattern that restricts the creation of instances of a class to a single instance and provides global access to that instance. In other words, the Singleton pattern ensures that there is only one instance of a given class in Java, and that instance is easily accessible from anywhere in the program.

What problem does the Singleton design pattern solve?

The Singleton design pattern is useful when you need to ensure that there is only one instance of a given class in an application. For example, you can use the Singleton pattern to ensure that there is only one instance of a database connection object, a logging object, or a configuration object in the application. This avoids wasting resources and ensures consistency in the application.

Example of a Singleton implementation in Java

We will now show you how to implement the Singleton pattern in Java.

We’ll create a class called Singleton.
In Singleton, we implement a private constructor that prevents direct instance creation.

Next, we need a variable for the instance itself, which we’ll call instance. The variable will be of type private static and will be initialized to null.

The getInstance() method will always be called to get an instance of the singleton. We create and program this so that if the instance does not already exist, it will be created on the first call to getInstance() and subsequent calls to getInstance() will return the same instance.

Add a showMessage public void method with any text to the class.

Singleton.java

package designpatterns;

public class Singleton {
    // Pretoze k tejto premennej pristupujeme zo statickej metody,
    // musi byt tiez staticka.
    private static Singleton instance = null;

    // Privatny konstruktor zabrani vytvoreniu instancie.
    private Singleton() {
    }

    // Pre pristup k instancii budeme pouzivat tuto metodu.
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

    // Metoda na verifikovanie volania metody na instancii.
    public void showMessage() {
        System.out.println("You have implemented design pattern Singleton.");
    }
}

Here is an example of how to use the Singleton class:

Main.java

import designpatterns.Singleton;

public class Main {
    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance();
        singleton.showMessage();
    }
}

This code prints the message “You have implemented the Singleton design pattern” because showMessage() is called on the Singleton instance.

We have prepared files with the above example Java Singleton code that you can run directly in Java. Download the code here.

About the author

Jozef Wagner

Java Developer Senior

Viac ako 10 rokov programujem v Jave, momentálne pracujem v msg life Slovakia ako Java programátor senior a pomáham zákazníkom implementovať ich požiadavky do poistného softvéru Life Factory. Vo voľnom čase si rád oddýchnem v lese, prípadne si zahrám nejakú dobrú počítačovú hru.

Let us know about you