0

In singleton design pattern, we restrict creation of objects to a single object using private constructor.

To provide a global handle to it, we use a "public static" method.

My question is why static is needed here? Why not just public?

Navin Israni
  • 1,327
  • 3
  • 15
  • 27
  • 7
    Make it an instance method; then try and use the singleton. Finding out for yourself is worth a thousand explanations - you might even be able to explain to somebody else someday... – Boris the Spider Oct 11 '16 at 07:44
  • I don't understand why do people down vote a valid question. It is a very valid question for someone trying to understand the concept. I guess I'm too sexy to be understood! :P :P – Navin Israni Oct 11 '16 at 08:05
  • Nope, this question bad and self answerable if one would spent time understanding what `static` means and how singleton works. Even the question "why not abstract" shows that you couldn't be bothered with doing research on your own to understand what `abstract` means. – Tom Oct 11 '16 at 08:08
  • @Tom I am a trainer by profession. I have been teaching these concepts since more than two years. It is possible for you to forget a few things learnt in your life back when you were a kid Last I knew this was a place for intelligent discussions. Never knew it turned political hell-hole so soon! – Navin Israni Oct 11 '16 at 08:13
  • I'm very sorry, but this sounds like a lie and if you really were a teacher, you were able to do proper research. But since a single downvote turns the whole page into a "political hell-hole" for you, I'm not going to keep commenting, so please no tears, ok? :). – Tom Oct 11 '16 at 08:45
  • I don't care what you think about me or this question. But why ruin my reputation? If you don't want to answer a question, simply avoid it. If an answer is wrong, down vote it. A comment is offensive, down vote it. But what does down voting a question mean! There are plenty of valid questions which may not be of "your level', it does not mean that question calls for a down vote. My question was basic, very basic - I understand, not ridiculous - and definitely not an assignment question (which is why the question down vote option was put there in the first place!) – Navin Israni Oct 11 '16 at 08:58
  • And as regards to you questioning my credentials as a teacher, I don't know who you are or what you do (developer or a trainer yourself!). But do you think teachers understand things automatically? Do you think Teachers should not ask doubts? If yes, then you should try to teach a class of undergrad students and try answering the doubts they come up - with a poker face expression without getting angry. – Navin Israni Oct 11 '16 at 09:01
  • A teacher has to do SO much of due diligence just for one topic! It's all behind the scenes, which sadly ignorant ppl who take things for granted will never understand! – Navin Israni Oct 11 '16 at 09:02

2 Answers2

3

Short answer:

Assume you have a Singleton class:

public class Singleton {
    ...
}

Then the constructor is probably private which means you cannot use new Singleton() from another class.

So the only way to access something that is inside the Singleton class would be using Singleton.methodName() or Singleton.fieldName.

But in order to do this then these methods and fields cannot be part of an object, they have to be static. And the getSingleton() or getInstance() method is no exception.

Answer with examples:

Assume you have a Singleton class:

public class Singleton {
    
}

We can now add the constructor. But it can not be public, since if it is public then you can just use new Singleton() from every other class and then it would not be a Singleton anymore. So the class would now look like this.

public class Singleton {

    private Singleton(){

    }

}

Now that the constructor is private this means that you cannot instantiate the class from another class it can also be instantiated from inside the Singleton class. So we should add the getInstance() or getSingleton() method.

public class Singleton {

    private Singleton(){

    }

    public Singleton getSingleton(){
        return null;
    }

}

But now we cannot access it since the getSingleton() method can only be used on an object and we cannot instantiate a Singleton object from outside the class. So the getSingleton() needs to be accessed by using Singleton.getSingleton() and therefore it has to become a static method.

public class Singleton {

    private Singleton(){

    }

    public static Singleton getSingleton(){
        return null;
    }

}

The answer so far should answer the question but it is not a functional Singleton class. So please continue reading for the complete answer.

Now we also want to return the instance of the Singleton from the getSingleton() method. So we also want a field called instance of singleton to point to the instance of the Singleton class.

public class Singleton {
    private Singleton instance;

    private Singleton(){

    }

    public static Singleton getSingleton(){
        return instance;
    }

}

But now the instance field is not accessible by the get getSingleton() method since the way the class is written right now the instance is a field of an the object and not the class, so the instance field has to become static as well.

public class Singleton {
    private static Singleton instance;

    private Singleton(){

    }

    public static Singleton getSingleton(){
        return instance;
    }

}

And now the final problem is that the variable instance is not instantiated anywhere so it will always return null. So we have to check in the getSingleton() that if the instance is null then create a new Singleton() and make the instance field point to it.

public class Singleton {
    private static Singleton instance;

    private Singleton(){

    }

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

}

If you want a thread safe Singleton class you can use something like this instead (suggested by Boris the Spider):

public enum Singleton {
    INSTANCE;
    private Singleton(){
        // TODO
    }    
}

And now the Singleton is complete.

Community
  • 1
  • 1
nick zoum
  • 7,216
  • 7
  • 36
  • 80
1

If the method is public and no static you will need an instance of the class to be able to call that method.. that makes no sense.

static method instead can be invoked with no instance since they belong the class

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • we can create an instance of the class and call the method, each call will still return the same instance anyways. – Navin Israni Oct 11 '16 at 07:48
  • @NavinIsrani so you create an instance to return a different instance of something for which there should only be one instance...? Do you see the problem? – Andy Turner Oct 11 '16 at 07:52
  • @NavinIsrani so you have a `private static final Singleton INSTANCE` which you return from a `public getInstance()` method; so to get the **single**, **`static`**, instance of your singleton you call `new Singleton().getInstance()`. That doesn't sound right to me; does it sound right to you? Furthermore, given that in any sensible singleton the ctor is `private`; how do you advocate creating the instance in the first place? – Boris the Spider Oct 11 '16 at 07:53
  • @BoristheSpider it does serve the purpose, it fulfills the definition completely i.e a single instance, shared by a public handle. – Navin Israni Oct 11 '16 at 07:55
  • @NavinIsrani nope. You just created a new instance to access the single instance. That is the **exact opposite** of a singleton. And if the reason that the singleton exists is scarce resource management, for example a SQL connection pool, most likely inited in the ctor; you also just created a new connection pool to access the singleton connection pool. – Boris the Spider Oct 11 '16 at 07:56
  • yeah. you are right .. so why don't we make the class abstract as well? static variable inside an abstract class accessible from a static method – Navin Israni Oct 11 '16 at 07:57
  • @BoristheSpider Does that make sense? – Navin Israni Oct 11 '16 at 07:59
  • @NavinIsrani you cannot create an instance of an `abstract` class, not even a single instance. Having a `private` ctor prevents any instantiation, so that is enough to control creation. Furthermore, in any sensible DI framework (Spring, Guice, etc) you would be injecting the `interface` and the DI framework would handle creation and management of the singleton instance; allowing for easy mocking during testing. In fact it is exactly mocking during testing that has led to the "singletons are evil" mantra. You cannot mock `Singleton.INSTANCE`. – Boris the Spider Oct 11 '16 at 08:00
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/125398/discussion-between-navin-israni-and-boris-the-spider). – Navin Israni Oct 11 '16 at 08:06
  • @BoristheSpider you perhaps never understood my question. Anyways I got my answer and chose it as final. :) – Navin Israni Oct 11 '16 at 08:11
  • @NavinIsrani of course I did; the fact that you didn't understand my response is not a reason to accuse me of ignorance. – Boris the Spider Oct 11 '16 at 08:12
  • @BoristheSpider the fact that you did not understand the reason behind asking a doubt is no reason to accuse me of mocking. – Navin Israni Oct 11 '16 at 08:16