Singleton Pattern in Java: Explanation & Practice

Implement the singleton design pattern

Problem summary

Create a Database class that can only have one instance. Return the same instance every time getInstance() is called.

Starter code

class Database {
    // Implement singleton pattern
    // Private static instance
    // Private constructor
    // Public static getInstance()
}

public class Main {
    public static void main(String[] args) {
        Database db1 = Database.getInstance();
        Database db2 = Database.getInstance();
        
        // Should print: Same instance: true
        System.out.println("Same instance: " + (db1 == db2));
    }
}

Expected output and test cases

  • Both references point to same instance
    Same instance: true

Hints

  1. Make constructor private
  2. Create private static instance variable
  3. Return instance in getInstance(), create if null

Related OOP Basics exercises

Practice all OOP Basics exercises · Run this idea in the Java compiler