Reputation: 809
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 ?
Upvotes: 2
Views: 22854
Reputation: 45
Here you are having getInstance()
as a static method and you have created method
as a non-static or instance method.
So for a static method, Class.method_name
format can be used, but for an instance method object needs to be created.
It may not be the correct syntax as shown over there:
Singleton.getInstance().method();
Singleton obj = new Singleton();
obj.method();
should be the correct format
Upvotes: 0
Reputation: 10009
First, you should make sure that you have declared your Constructor
as a private one to prevent any one to call it and re-initialize it again. As following:
private void Singleton(){
//Initialize your private data
}
Second, call the static
methods directly as following:
Singleton.yourMethod();
Third:, the non-static method calling as following:
Singleton.getInstance().yourMethod();
Here is a good Example of the Singleton
classes
Upvotes: 2
Reputation: 63955
The singleton pattern allows you to control the amount of instances that exist of one class - i.e. just 1. But the class itself is still a normal class that is not supposed to know how many of it's kind exist and it should therefore have normal instance methods.
When using static
methods, you'll run into terrible problems if you ever want to change how many instances of that class exist.
Either use a singleton or use static methods.
Upvotes: 2
Reputation: 8153
If you want to use Singleton pattern:
public class Singleton {
private static Singleton sInstance;
public static Singleton getInstance() {
if (sInstance == null) {
sInstance = new Singleton();
}
return sInstance;
}
// Prevent duplicate objects
private Singleton() {
}
public void method() {
}
}
Upvotes: 2
Reputation: 17401
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();
Upvotes: 12
Reputation: 2780
Singleton.getInstance().method();
is better as when called for first time instance will be null and instance is only created in getInstance().
Upvotes: 0
Reputation: 157457
In the first case:
Singleton.method();
method have to be static
In the second case:
Singleton.getInstance().method();
the method is not static.
So those are conceptually different
Upvotes: 1