Can we define a Singleton class without having getInstance() method?
public class Singleton {
public static final Singleton singleton = new Singleton();
private Singleton(){
}
}
Can we define a Singleton class without having getInstance() method?
public class Singleton {
public static final Singleton singleton = new Singleton();
private Singleton(){
}
}
You should separate the concept of an object that only has a single instance from the singleton pattern. You can find a discussion of the two here and here. TL;DR Single instance is useful, while using the singleton pattern is bad.
The best way to use a single-instance object in your code is to pass it via ctor. This is easier with a dependency injection framework, but works without, too.
class Something
{
private IMySingleInstance _single;
public Something(IMySingleInstance s)
{
_single = s;
}
}
If you do it like that, you declare the dependency, and you can actually test your Something and mock the single instance if necessary without all the problems related to the singleton pattern.