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
- Make constructor private
- Create private static instance variable
- Return instance in getInstance(), create if null
Related OOP Basics exercises
- Practice Rational Number Class in Java
- Practice Music Playlist Manager in Java
- Practice Factory Pattern in Java
Practice all OOP Basics exercises · Run this idea in the Java compiler