Creational Design Patterns : Singleton

Creational Design Patterns : Singleton

The Singleton design pattern illustrated with Java

In the world of software engineering, design patterns serve as essential templates for solving commonly encountered problems. One such design pattern is the Singleton, this pattern ensures that a class has only one instance and provides a single point of access to it for any other code.

Creational design patterns are a subset of design patterns that are concerned with the creation of objects, In this post, we are going to be discussing the Singleton pattern and explore its implementation using Java.

The singleton pattern is a creational design pattern that falls under the Gang of Four design patterns. Its primary objective is to ensure that a class has only one instance and that one instance is globally accessible, every time an object of that class is needed, the exact same instance is used. This pattern is often used when a single object is required to coordinate actions across the system, like a shared resource. For example, database connections or logging objects.

Before delving into code, let's outline the components of our Singleton class.

  1. A private static field variable to hold our instance.

  2. A private constructor to prevent object instantiation from outside.

  3. A public static method that returns our instance.

These are the building blocks of a Singleton, now to some coding!

public class MySingleton {
    private MySingleton instance;

    private MySingleton() {
        //instantiation logic here.
    }
    public static MySingleton getInstance() {
        //lazy initialisation
        if(instance == null){
            instance = new MySingleton();
        }
        return instance;
    }
}

To use the above Singleton, you could do something like this:

var instance = MySingleton.getInstance();

This would create the instance if not yet created, then return the same instance every time you call it.

Performance: Creating and destroying objects can be expensive, using a singleton ensures only one object is created for that class, this improves performance by eliminating the need to create multiple instances of the same object.

Global point of access: The singleton design pattern provides a single global point of access to a resource, making it easy to manage and share the resource throughout the application.

Thread Safety: Singletons can be implemented in a thread-safe way, ensuring concurrent access to the singleton resource does not cause problems. Please note, that the above example is not implemented in a thread-safe manner, we can explore thread-safety in a future post.

By implementing the singleton design pattern, software engineers can better manage resources and improve the overall structure and performance of their software applications.

This is the first of a three-part series, we will be discussing other creational design patterns: Builder and Factory design patterns.