4

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.

Community
  • 1
  • 1
Nitish
  • 13,487
  • 26
  • 128
  • 252

6 Answers6

12

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

Sarthak Mittal
  • 5,384
  • 2
  • 20
  • 41
5

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.
retroq
  • 562
  • 2
  • 7
3

Can singleton class have multiple instances?

Ans: NO

This is the simple example for Singleton class in java. By calling Singleton.getInstance() you can get the instance of this Singleton class. Here instance is private static and constructor is private so only one object is available per JVM.

 public class Singleton {    

        private static Singleton instance = new Singleton ();

        private Singleton () {
        }

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

Lazy instantiation to create the singleton also known as classic singleton and it is not a thread safe version

public class Singleton {    

            private static Singleton instance = null;

            private Singleton () {
            }

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

A thread safe lazy initialization singleton class can be implemented in a simple way as follows

public class Singleton {
    private Singleton() {}

    private static class LazyHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return LazyHolder.INSTANCE;
    }
}
Sagar Pudi
  • 4,396
  • 3
  • 31
  • 51
  • The lazy version is not thread safe. It's possible to get multiple instances if multiple threads access getInstance(). I suspect the interviewer was digging for thread awareness. See http://stackoverflow.com/a/16106598/1168342 – Fuhrmanator Nov 27 '14 at 17:14
3

I'm styding for the Architect certification and this question came up.

I believe this is better answered when you go to the source, which I believe to be the book [Design Patterns: Elements of Reusable Object-Oriented Software] by Erich Gamma / Richard Helm / Ralph Johnson / John Vlissides. I did a quick research and didn't find this defined earlier than the book release.

Although at the beginning (page 127) it states that the intent is to "Ensure a class only has one instance, and provide a global point of access to it.", on the section 'Consequences', bullet 4, it has the variation "Permits a variable number of instances. The pattern makes it easy to change your mind and allow more than one instance of the Singleton class. Moreover, you can use the same approach to control the number of instances that the application uses. Only the operation that grants access to the Singleton instance needs to change."

With that said, I believe that the formal answer is that the singleton CAN have multiple instances, although I particularly don't see this being applied in the real world (by the way whoever put this in your interview doesn't seem really interested in assessing your useful skills).

1

I know it is an old one but I hope I'll help others out.

Sadly the Singleton pattern has got many definitions. Examples:

Definition 1 HTDIN:

Singleton pattern is a design solution where an application wants to have one and only one instance of any class, in all possible scenarios without any exceptional condition.

Definition 2 Wikipedia:

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

The first one is more strict but if you look at the second description is states that there could be multiple instances. This way you are able to do something like pooling.

final class Singleton {
    private static int ROUND_ROBIN_COUNTER = Integer.MAX_VALUE;
    private static final List<Singleton> INSTANCES = Arrays.asList(new Singleton(), new Singleton(), new Singleton());

    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCES.get(Math.abs((ROUND_ROBIN_COUNTER++)%INSTANCES.size()));
    }
}

According to the first definition this is not a singleton, but the second one allows that. I am reading the OCM Java EE 6 Enterprise Architect Exam Guide it also agrees with the Wikipedia definition.

Hash
  • 4,607
  • 5
  • 20
  • 39
1

It's a good theoretical question, but the definition states very clearly that the pattern 'Ensure a class only has one instance'. You can build an almost identical pattern which allows you to instantiate maximum, let's say, 4 objects of the same type.

In that case, the definition of the pattern would have to be 'Ensure a class only a limited number of instances'.

You can look at the problem form a different angle. You would have to hold those 4 objects in a data structure. Either as hardcoded separate members(instance1, instance2,...) or in a list. In the second case, the list could be considered the singleton.

adiian
  • 1,297
  • 2
  • 15
  • 31