0

Below is a class using the singleton design pattern:

class Singleton
{
    private static Singleton instance;
    private Singleton()
    {
        ...
    }

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

        return instance;
    }
    ...
    public void doSomething()
    {
        ... 
    }
}

I wanted to know some design issues about the above class? Why is the instance variable instance private and static. I understand that being private make the instance variable accessible only to object of that specific class but how does it help?

Andy
  • 8,054
  • 5
  • 35
  • 71
Noor
  • 18,061
  • 35
  • 123
  • 236
  • Added Java since I'm not aware of the synchronized keyword in c#. – Andy May 12 '13 at 15:31
  • Do you really need to instantiate it lazy? – NilsH May 12 '13 at 15:33
  • @NoobUnChained i disagree this is a dup. He's asking if there is anything wrong with this particular implementation, not what abuses of singleton could come about. – Andy May 12 '13 at 15:36

1 Answers1

6

If it was public, everybody could use Singleton.instance and would complain because it's null. Making it private forces them to use getInstance(), which guarantees to return a non-null instance.

If it wasn't static, it would be an instance variable of Singleton, and you would thus need a Singleton instance to access the unique Singleton instance which doesn't make much sense.

VorobeY1326
  • 772
  • 10
  • 25
JB Nizet
  • 633,450
  • 80
  • 1,108
  • 1,174