Design Pattern: Singleton Pattern

Summary

Pattern NameSingleton Pattern
Pattern TypeCreational Pattern
ScopeObject
TaglineEnsure only one instance of a class
Use casesWhen we want to ensure that only one instance of a class
is created in any case (Like for, Database connection, File handler, etc.)
Related PatternsAbstract Factory
Builder
Facade
Flyweight
Prototype
Difficulty LevelEasy
Implementations

Definition

Singleton pattern is used to ensure that only one instance of a class is created in any case, and whenever you want to get an instance of that class, then the same object instance is returned. Singleton pattern also ensures easy global access to the singleton object.

Say, you want to handle a database connection or a file resource – in that case, you don’t need to create a new object each time. As you want the database connection or the file resource to point to the same connection/resource always.

Implementation

Implementation of Singleton pattern is simple and involves only one class (the Singleton class).

Use the following steps to implement Singleton pattern.

Step #1: Prevent the creation of new instances manually

The constructor needs to be private so that a new instance of the class can not be created by using new operator.

Step #2: Make sure the instance is accessible from anywhere

Create a static method for getting the instance of that class. This static method will accept the parameters required to create a new instance of the class.

Step #3: Ensure to return of the same instance each time

  • Use a class variable to store instances.
  • If an instance already exists then return that from the static method.
  • If no instance exists- then create a new instance, store the instance in the class variable, and return that instance from the static method.

Examples

Example #1: Database Connection

Let’s take the example of creating a class for database connection.

Singleton Class

final class DbConnectionSingleton

    var static dbInstance: DbConnectionSingleton
    var url: String
    var port: String
    var username: String
    var password: String

    // Make sure to make it private, so that the constructor can be used directly
    private function DbConnectionSingleton(
        urlParam: String,
        portParam: String,
        usernameParam: String,
        passwordParam: String
    )
       url = urlParam
       port = portParam
       username = usernameParam
       password = passwordParam
    end function

    // Make this function static to access it directly
    static function getInstance(
        urlParam: String,
        portParam: String,
        usernameParam: String,
        passwordParam: String
    ): DbConnectionSingleton

        if (dbInstance == null)
            dbInstance = new DbConnectionSingleton(urlParam, portParam, usernameParam, passwordParam)
        end if

        return dbInstance
    end function

   // Utility function for printing connection information
   function printConnectionDetails()
        print("URL:" + url)
        print("Port:" + port)
        print("User name:" + username)
        print("Password:" + password)
    end function

    // Utility function for processing query (dummy)
    function executeQuery(String query: String)
        print("Executing query: " + query)
    end function

end class

Demo

// Create an instance of the connection
var dbConnection: DbConnectionSingleton = DbConnectionSingleton.getInstance("localhost", "5432", "postgres", "secret*pass")

print("First Connection Details:")
dbConnection.printConnectionDetails()

// Try creating another connection. This will return the previous existing connection
var secondDbConnection: DbConnectionSingleton = DbConnectionSingleton.getInstance("192.168.55.55", "1234", "postgres2", "secret*pass2")
        
print("Second Connection Details:")
secondDbConnection.printConnectionDetails()

Output

First Connection Details:
URL:localhost
Port:5432
User name:postgres
Password:secret*pass


Second Connection Details:
URL:localhost
Port:5432
User name:postgres
Password:secret*pass

Code Implementations

Use the following links to check Singleton pattern implementation in specific programming languages.

Leave a Comment