Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: getInstance vs Static

What is the purpose of getInstance() in Java?

During my research I keep reading that getInstance() helps achieve a Singleton design pattern (which means just one instance across the whole program to my understanding). But can't I just use static? Isn't that the whole point of static?

If I were to just have static methods and fields, how would it differ from using getInstance()? Is there a "scope" of static? For example, one instance per method or class?

And if they are different, in what cases would I choose getInstance() over using static?

I apologize if the question is unclear, I am sure I am missing something on the subject matter, I just can't figure out what.

Thank you for any and all advice.

like image 871
FreakyDan Avatar asked Jun 13 '14 21:06

FreakyDan


People also ask

Why is getInstance static?

for a singleton pattern, getInstance IS a static method, and uses static attrs. The whole point of static is to have things associated with the class instead of a specific object. The singleton pattern guarantees that you will have one instance of an object of that type.

Why getInstance is static in singleton?

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.

What is getInstance Java?

The getInstance(Locale locale) is the method of Java Currency class which is used to get an instance of currency for the given country. Because countries change their currencies, the result may vary over time.

Should I use a static class or a singleton?

A Singleton can implement interfaces, inherit from other classes and allow inheritance. While a static class cannot inherit their instance members. So Singleton is more flexible than static classes and can maintain state. A Singleton can be initialized lazily or asynchronously and loaded automatically by the .


4 Answers

Static will not give you a singleton. Since there is no way of making a top-level class a singleton in Java, you have getInstance methods which will implement some logic to to be sure there is only one instance of a class.

public class Singleton {     private static Singleton singleton;     private Singleton(){ }     public static synchronized Singleton getInstance( ) {       if (singleton == null)           singleton=new Singleton();       return singleton;    }  } 

Check out this top answer: Static Classes In Java

The above code will allow only one instance to be created, and it's clean, however as of Java 1.6, it is better to create singleton's as such since it is slightly more elegant IMHO:

public enum MyEnumSingleton {     INSTANCE;      // other useful methods here }  

Source: http://www.vogella.com/tutorials/DesignPatternSingleton/article.html

like image 117
Zac Lozano Avatar answered Sep 19 '22 19:09

Zac Lozano


Singleton

A singleton allows you to use a single reference to a java Object. For example, here is a singleton which contains a number;

public class MySingleton {      private int myNumber;     private static MySingleton instance;      public static MySingleton getInstance() {         if (instance == null) {              instance = new MySingleton();         }         return instance;     }      private MySingleton() {}      public void setMyNumber(int myNumber) {         this.myNumber = myNumber;     }      public int getMyNumber() {        return myNumber;     } } 

Now we are going to set the value of this number in the A class:

public class A {     /*...*/     MySingleton mySingleton = MySingleton.getInstance();     mySingleton.setMyNumber(42);     /*...*/ } 

Then, you can access this value from another class:

public class B {     /*...*/     MySingleton mySingleton = MySingleton.getInstance();     int number = mySingleton.getMyNumber();     /*...*/ } 

In this class the number variable will have the value 42. This is the advantage of a singleton over a simple object:

All the values stored in the singleton will be accessible from "everywhere".


Static class

The purpose is different, here the advantage is to use an object without having to create it.

For example:

public static class MyStaticClass {     public static void sayHello() {         System.out.println("Hello");     } } 

Now you can use the sayHello() method from any classes by calling:

MyStaticClass.sayHello();  
like image 28
G.T. Avatar answered Sep 18 '22 19:09

G.T.


The exact method of implementing a singleton, for example using a factory method called getInstance(), isn't that relevant to the question, which is "static methods vs singleton with instance methods".

Classes are themselves effectively singletons, so from that aspect they are similar.

The main difference is that static methods are not part of class hierarchy - they are not inherited, which means the static method option locks you forever to using that exact class and it can't be referred to in any other way, such being an implementation of some interface or a super class.

Instances however don't have this problem, so you can code for example:

class MySingleton implements SomeInterface {
    ...
}

SomeInterface instance = MySingleton.getInstance();
like image 34
Bohemian Avatar answered Sep 20 '22 19:09

Bohemian


I prefer to use static too, but sometimes getInstance() is helpful to have some functions that will be related to the object, in which you can modify variables. if you are simply making some util functions that do not need an instance of an object, use static.

When you are using someone's libraries, you never know if a function body needs a class instance. That's why a lot of library classes are using getInstance().

like image 35
Victor2748 Avatar answered Sep 16 '22 19:09

Victor2748