Singleton Pattern

Dana Prata
3 min readJun 5, 2023

--

In Theory

The Singleton pattern is a creational design pattern that ensures that ONLY ONE INSTANCE of a class is created and provides A GLOBAL POINT OF ACCESS to that instance.

Here’s a simple explanation with a Java example:

public class Singleton {
private static Singleton instance;

// Private constructor to prevent external instantiation
private Singleton() {
}

public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}

// Other methods of the Singleton class
public void doSomething() {
// ...
}
}

In this example, the Singleton class has a private constructor, which means it cannot be directly instantiated from outside the class. The class also has a static method getInstance() that returns the instance of the class.

The getInstance() method first checks if an instance of the class already exists. If not, it creates a new instance using the private constructor. Subsequent calls to getInstance() will return the same instance, ensuring that only one instance is created throughout the program.

Here’s how you can use the Singleton class:

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

In the main() method, we call getInstance() to obtain the instance of the Singleton class. We can then use this instance to invoke methods or access variables within the class.

In Practice

There are several situations where using a Singleton class can be beneficial. Here are a few examples:

  • Database Connection Pool
  • Configuration Settings
  • Caching
  • Thread Pool

I’ll go further with the database connection pool situation. The Singleton pattern can be useful when connecting to a database because it allows you to have a single, shared database connection instance that can be accessed from different parts of your application.

Here’s a simple example of using the Singleton pattern to connect to a database:

public class DatabaseConnection {
private static DatabaseConnection instance;
private Connection connection;

private DatabaseConnection() {
// Initialize the database connection
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
} catch (SQLException e) {
e.printStackTrace();
}
}

public static DatabaseConnection getInstance() {
if (instance == null) {
instance = new DatabaseConnection();
}
return instance;
}

public Connection getConnection() {
return connection;
}

// Other database-related methods
public void executeQuery(String query) {
// ...
}
}

In this example, the DatabaseConnection class follows the Singleton pattern. The private constructor ensures that the class cannot be directly instantiated from outside. The getInstance() method returns the instance of the class and creates it if it doesn't exist.

The DatabaseConnection class also has a getConnection() method that returns the connection object, which can be used to execute database queries. You can add other database-related methods to this class based on your requirements.

To use the DatabaseConnection class:

public class Main {
public static void main(String[] args) {
DatabaseConnection databaseConnection = DatabaseConnection.getInstance();
Connection connection = databaseConnection.getConnection();

// Use the connection to execute queries or perform database operations
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM mytable");

// Process the result set
while (resultSet.next()) {
// ...
}

// Close the result set, statement, and connection
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

In the main() method, we obtain the DatabaseConnection instance using getInstance(). We can then use the getConnection() method to get the actual connection object and perform database operations using it.

By using the Singleton pattern, we ensure that there is only one instance of the DatabaseConnection class, and all parts of the application can share the same database connection, preventing the unnecessary creation of multiple connections.

Thank you for reading! 👏

--

--

Dana Prata

👩‍💻Senior Software Engineer | 🎉Tech Enthusiast