Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Object is made static in Singleton pattern?

Why is the Object made static in the Singleton pattern?
What is actual use of it?
What will happen if we don't make object static?

public class SingleObject {

   //create an object of SingleObject
   private static SingleObject instance = new SingleObject();

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}

   //Get the only object available
   public static SingleObject getInstance(){
       return instance;
   }

   public void showMessage(){
       System.out.println("Hello World!");
   }
}
like image 570
nilesh Avatar asked Nov 18 '14 11:11

nilesh


2 Answers

You usually keep the single instance of the Singleton class in a static variable of that class. This doesn't make that instance static. Only the reference to it is static.

Since you can only obtain that single instance via a static method of the class (you can't explicitly construct instances of a Singleton class via a constructor - otherwise it wouldn't be a singleton), the reference to that instance must be stored in a static variable.

like image 116
Eran Avatar answered Sep 20 '22 10:09

Eran


Just adding/elaborating eran's answer,since getInstance method is static method, getInstance method can be called from main methods/other methods by using classname i.e. SingleObject.getInstance(); This means you will never need an object reference to call getInstance()

If it would have been instance method , you would have needed an object to call getInstance. Now there is no way to create an object of class SingleObject outside the class (since constructor is private ) & this is the real trouble.

Conclusion 1: This means we need to have a static method.

Conclusion 2: SO NEED TO HAVE A STATIC METHOD, MAKES THE PROPERTY TO BE STATIC, since instance property is not available inside static method.

like image 29
ASharma7 Avatar answered Sep 22 '22 10:09

ASharma7