Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple instances of Singleton class. Possible?

I found this explanatory link which states

Ensure a class has one instance, and provide a global point of access to it.

I recently appeared at an interview and to my surprise it was asked from me too that can singleton class have multiples instances, my technology being Java and Objective C. My answer to this question was NO which I believe is right as Singleton variable being global shall check if it is null or not. And it will be null only the first time.
However out of curiosity I was confirming it. Can someone provide a confirmation with explanation weather I am right or wrong.

like image 348
Nitish Avatar asked Nov 29 '22 07:11

Nitish


2 Answers

The word Singleton by definition(of Design Patterns) does not allows multiple instances, but yeah you can tweak the class to create multiple instances but then it won't be considered as a Singleton by definition

like image 97
Sarthak Mittal Avatar answered Dec 16 '22 00:12

Sarthak Mittal


Well-designed singleton can have only one instance per application. Creating of multiple instances is a mistake in the application design. It might happen in some cases, e.g.:

  • Non thread safe singleton with lazy initialization: several threads are trying to get an instance and creates multiple instances. Good practice for lazy singleton is init on demand
  • When using DI containers for managing singletons (Spring for example) and several contexts every context will create his own instance of class.
like image 23
retroq Avatar answered Dec 15 '22 23:12

retroq