What is Singleton Class? How to Use?

“Good morning, and in case I don't see ya: Good afternoon, good evening, and good night!”

The Truman Show (1998)

What I learned in this chapter of Effective Java was how to use singleton classes more effectively. I just wanted to share it. First of all, what is a singleton class? I want to examine what it is used for.

Singleton means singularity. This name, which comes from its work, is tied to the principle that the object is created only once. Each new class creation will point to a new area in memory, and in some cases, I may want to use a previously created class instead of creating a new one. For example; I opened a database connection, I don't need to open it again and again, I can use the same connection. I'm dealing with file operations.

public class DBConnector {
    private static final DBConnector dbConnectorInstance = new DBConnector();

    private String url = "jdbc:postgresql://localhost:5432/jdbc";
    private String username = "root";
    private String password = "localhost";

    private DBConnector() {}

    public static DBConnector getInstance(String url, String username, String password) {
        dbConnectorInstance.url = url;
        dbConnectorInstance.username = username;
        dbConnectorInstance.password = password;

        return dbConnectorInstance;

I already have a pre-created class. I equip this class with the features I want and use them again and again. By "private static final" of our class that I want you to pay attention to here, we guarantee that our class will always have the same object reference.

DBConnector dbConnector = DBConnector.getInstance("db-url", "emreyildirim","*****");

Did you notice? There is no public constructor in our class. So I want an instance of the object related to getInstance, not a new object with the new keyword. You might want to take a look at how this happens in my post Static Factory Method vs Constructor. We can use Static Factory to control the object to be returned using the getInstance method. eg:

public class DBConnector {
    private static DBConnector dbConnectorInstance;

    public static DBConnector getInstance(String url, String username, String password) {
        if (dbConnectorInstance == null) {
            DBConnector dbConnector = new DBConnector();
            dbConnector.url = url;
            dbConnector.username = username;
            dbConnector.password = password;
            dbConnectorInstance = dbConnector;

        return dbConnectorInstance;
JavaEffective JavaCreating and Destroying ObjectsDesign PatternsSingleton ClassSingularityInstance