Design Pattern: Singleton Pattern in Java

Singleton pattern is used to ensure that, only one instance of a class can be created.

Check complete details and explanations about the Singleton pattern in the article: Singleton Design Pattern

This article demonstrates Singleton pattern implementations in Java. Check the following examples.

Example #1: Database Connection

Let’s take the example of creating a class for database connection. Take a look at the class diagram.

Singleton Class


package com.bigboxcode.designpattern.singleton.dbconnection;

public final class DbConnectionSingleton {

    private static DbConnectionSingleton dbInstance;
    private String url;
    private String port;
    private String username;
    private String password;

    private DbConnectionSingleton(String url, String port, String username, String password) {
        this.url = url;
        this.port = port;
        this.username = username;
        this.password = password;

    public static DbConnectionSingleton getInstance(String url, String port, String username, String password) {
        if (dbInstance == null) {
            dbInstance = new DbConnectionSingleton(url, port, username, password);
        return dbInstance;

    public void printConnectionDetails() {
        System.out.println("URL:" + url);
        System.out.println("Port:" + port);
        System.out.println("User name:" + username);
        System.out.println("Password:" + password);

    public void executeQuery(String query) {
        System.out.println("Executing query: " + query);



package com.bigboxcode.designpattern.singleton.dbconnection;

public class Demo {
    private static final String DB_URL = "localhost";
    private static final String DB_PORT = "5432";
    private static final String DB_USERNAME = "postgres";
    private static final String DB_PASSWORD = "secret*pass";

    private static final String DB_URL2 = "";
    private static final String DB_PORT2 = "1234";
    private static final String DB_USERNAME2 = "postgres2";
    private static final String DB_PASSWORD2 = "secret*pass2";

    public static void main(String[] args) {
        DbConnectionSingleton dbConnection = DbConnectionSingleton.getInstance(DB_URL, DB_PORT, DB_USERNAME, DB_PASSWORD);
        System.out.println("First Connection Details:");

        DbConnectionSingleton secondDbConnection = DbConnectionSingleton.getInstance(DB_URL2, DB_PORT2, DB_USERNAME2, DB_PASSWORD2);
        System.out.println("\n\nSecond Connection Details:");


First Connection Details:
User name:postgres

Second Connection Details:
User name:postgres

Source Code

Use the following link to get the source code:

Leave a Comment