-3

I'm a newbie in JAVA.

When I read about singleton pattern, It need an instance first run.

Something like that:

public class Singleton {

    private static final Singleton instance = new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
        return instance;
    }

}

But I also write something like that:

public class Singleton {


    public Singleton(){}
    //methods,....

}

So I have some question:

1) Why we need an instance in singleton? what's the purpose? 2) Why the constructor in singleton is private? How we can intialize input for this class?

I know my question is very basic, and hear so noop.

But please help me to explain them.

Thanks & Best Regards

phuong
  • 273
  • 1
  • 2
  • 10
  • 2
    It sounds like you basically need to read up more about what the singleton pattern is. Your second class isn't a singleton at all. – Jon Skeet Apr 05 '17 at 09:57
  • 2
    `When I read about singleton pattern, It need an instance first run` Did you finish reading about singletons? Your questions are usually answered in tutorials/lessons as they are the principle behind the singleton pattern – BackSlash Apr 05 '17 at 09:57
  • 1
    Possible duplicate of [Singleton class in java](http://stackoverflow.com/questions/2111768/singleton-class-in-java) – freedev Apr 05 '17 at 09:59
  • A singleton by definition has one instance. What are you asking? – khelwood Apr 05 '17 at 10:02

2 Answers2

1

1) the Singleton pattern is a design pattern where you only have one instance, i.e. one object, through the lifecycle of a program. So you make the instance static and initialize it once so you have that only one object in the program.

2) The constructor must be private so you don't initialize objects as much as you want. That is, when the constructor is private, you cannot call new Singleton() because you can't access the constructor from outside the class as it is private one. You can initialize input by making a static method that takes some parameters and create them when constructing the only instance

For example, consider the following

public class Singleton {

    private static Singleton instance;

    private String a;
    private String b;

    private Singleton(){}

    private Singleton(String a, String b) {
         this.a = a;
         this.b = b;
    }

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

}

Hope this helps!

Omar El Halabi
  • 2,118
  • 1
  • 18
  • 26
0

Don't use a public constructor in a singleton. The sense of a singleton is that you just have one instance of that class. So if you have a public constructor you can't guarantee that there is only one instance. You have the private constructor which is only called one time in that class, so you just have one instance. You provide that instance via the getInstance-Method.

Markus
  • 1,141
  • 1
  • 9
  • 25