javasingletonsingleton-methods

Best way to call a method inside a singleton class


I have a singleton class

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

Consider a public function method() is defined inside the class Singleton.

Which is the best way to call a method inside a singleton class:

Singleton.method() - method calling statically

or

Singleton.getInstance.method() - method not static ?


Solution

  • In case of singleton classes there is no use of static methods as there is only one instance available of the class and every buddy is having the same copy of it.

    so always create an instance method and call:

    Singleton.getInstance().method();