Singleton (One of a Kind Objects): Design Pattern[Part-4]

If you already know about Singleton, this blog is specially for you becasue we are gonna discuss something new here, which doesn’t get much attention.

What is a Singleton Pattern?

Singleton stands for “One and only One”. So, Singleton Pattern stands for “There is One and only One way to perform a task.

In terms of Object-Oriented Programming, The intent of Singleton Pattern is

  1. Ensure a class has only one instance, and provide a global point of access to it.
  2. Encapsulated “just-in-time initialization” or “initialization on first use”.
https://www.tutorialspoint.com/python_design_patterns/python_design_patterns_singleton.htm

Now, Before diving deep into it, Why do we need Singleton Pattern?

That’s a very good question. I mean what are we gonna achieve with this?

The purpose of the singleton pattern is to control object creation, limiting the number of objects to only one.

  1. Less be the number of instances, less memory management needs to be done by the system as well as your own garbage collection logic.
  2. Moreover, the management/handling of resources becomes easy too.

Singletons are often useful where we have to control the resources, such as database connections or sockets. Typically singletons are used for global configuration.

Some other example could be:

  • Hardware access
  • Database connections
  • Config files

How does it look like?

Here is the basic implementation. It can be implemented in 2 ways.

Eager initialization:

In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class.

public final class Singleton {
private static Singleton instance = new Singleton();;

private Singleton() {}

public static Singleton getInstance(String value) {
return instance;
}
}

Lazy initialization:

Opposite to Eager initialization, here we are going to initialize a new instance of the class in the getInstance() method itself. This method will check if there is an instance of that class is already created? If yes, then our method (getInstance()) will return that old instance, and if not then it creates a new instance of the singleton class.

public final class Singleton {
private static Singleton instance;

private Singleton() {}

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

Is there any issue with this Pattern?

When we say, only one object instantiation, that means, it has to be only one across the execution Or among multiple users. But one of the pattern’s consequences is the option to control the number of instances, should not affect the instance state. it should ensure the uniform state of resource across multiple users.

For example: Let’s consider the below case exception steps

User 1: DBConnection s1 = DBConnection.getInstance();
User 2: DBConnection s2 = DBConnection.getInstance();
User 1: s1 = null;
User 2: s1.open(); // gives null pointer exception

Now, user 2 doesn’t know that user 1 has made the instance NULL, so he has to manually take care of such cases.

In some programming languages like JAVA, concurrency can easily be handled using inbuilt libraries , but what about other technologies?

It’s a traditional problem of the critical section where more than one user tries to access a resource. So, we can use some Locking algorithm, or some semaphores’ approach to assign the instances according to priority and keep others in the queue so that, they will get the resource, once the first guy leaves it.

Or, Instead of doing the overhead of maintaining the queue Or something, we can let the user poll every time, whenever they want the resource. If the resource is occupied, they will not be getting the access else they get it, something like below

public final class Singleton {     private static Singleton instance;
public static Boolean isAvailable = true;
private Singleton() {} public static Singleton getInstance(String value) {
if(isAvailable){
if (instance == null) {
instance = new Singleton();

}
isAvailable = false;
return instance;
}
return null;
}
}

The issue with both the approaches is, how will the system come to know, that the instance has become free, and is available for others.

  1. One option could be, user forcefully themselves take care of freeing up the resource, but setting isAvailable= true.
  2. We can create a Destructor.

Conceptually there is no point in having a destructor in a design pattern, but if needed, we can use it.

public final class Singleton {     private static Singleton instance;
public static Boolean isAvailable = true;
private Singleton() {} public static Singleton getInstance(String value) {
if(isAvailable){
if (instance == null) {
instance = new Singleton();

}
isAvailable = false;
return instance;
}
return null;
}
public static void destructor(){ isAvailable = true;
}
}

However, the destructor call needs to be triggered at some point, so that the destruction can happen. What could be the trigging point?

Do we need to destroy the instance? if Yes, Who deletes/kills Singleton instances, and how, and when?

I’d argue that no, you can’t destroy a singleton because there needs to be exactly one instance of it available at all times. And arguably it needs to be the same instance because otherwise, it’s not really a singleton (e.g. two different classes could hold references to distinct instances of the class).

Although destruction is a debatable topic, so If you think, destruction is valid or invalid, Please put your feedbacks in comments. Let’s do a discussion. who knows, we might get some conclusion.

Keeping the issues aside, let’s see some Singleton pattern Implementations in different technologies.

Now depending on the technologies, the implementation varies with some modifications.

In Apex, It remains as it is.

public final class Singleton {
private static Singleton instance;

private Singleton() {}

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

In Java, to ensure it works with multithreading and remain thread-safe, the implementation changes like below

public final class Singleton {
private static volatile Singleton instance;

private Singleton() {}

public static Singleton getInstance(String value) {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

In Javascript,

var SingletonFactory = (function(){
function SingletonClass() {
//do stuff
}
var instance;
return {
getInstance: function(){
if (instance == null) {
instance = new SingletonClass();
instance.constructor = null;
}
return instance;
}
};
})();

In Python

class Singleton:
__instance = None
@staticmethod
def getInstance():
""" Static access method. """
if Singleton.__instance == None:
Singleton()
return Singleton.__instance
def __init__(self):
""" Virtually private constructor. """
if Singleton.__instance != None:
raise Exception("This class is a singleton!")
else:
Singleton.__instance = self

In C#

using System;public class Singleton {
private static Singleton mInstance;
private Singleton () { // Private Constructor
}

public static Singleton Instance {
get {
if( mInstance == null ) {
mInstance = new Singleton();
}
return mInstance;
}
}

}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vimal Tiwari

Vimal Tiwari

Engineer @Google | Content Creator (Linkedin, Quora & Medium) | https://vimaltiwari2612.github.io