I want to know, how to use the singleton pattern with interfaces? I have created an interface:
public interface BusinessService {
BusinessService getInstance();
}
I make this implementation:
public class BusinessServiceImpl implements BusinessService {
private static BusinessServiceImpl instance = null;
private BusinessServiceImpl(){ }
@Override
public BusinessServiceImpl getInstance() {
if (instance == null) {
BusinessServiceImpl.instance = new BusinessServiceImpl();
}
return BusinessServiceImpl.instance;
}
}
How can I get access to getInstance from my main-class? I tried something like
private BusinessService service = new BusinessServiceImpl();
(does not work - Constructor from BusinessServiceImpl() is private)
But what else? Can you help me out?
Edit: I'm using Java Spring! I don't want to use Java Springs - Dependency Injection!
Greets, Mira
The code you have provided is a bit mixed - up.
The whole point of controlling the instantiation of your singleton class means that you have to hide your constructor, so clients can't access it and create new instance at will.
Your factory method (a method, that creates the instance of your class) getInstance()
is an instance method. You have to create a new instance of BusinessService
in order to create an instance of BusinessService
- it's pretty obvious that won't work properly.
You have a few options to deal with your situation:
Remove the getInstance()
method from your interface and expose it in your implementation class as a static method. You should also limit the visibility of the constructor to private
.
public class BusinessServiceImpl implements BusinessService {
public static BusinessServiceImpl getInstance() {
// instantiation logic
}
private BusinessServiceImpl() {
// constructor logic
}
}
Use a factory class to instantiate your service and control the number of instances. This includes removing the getInstance()
method all together and limiting the visibility of your BusinessServiceImpl
class to package
.
class BusinessServiceImpl implements BusinessService {
BusinessServiceImpl() {
// constructor logic
}
}
// should be in the same package as BusinessServiceImpl
public final class BusinessServiceFactory {
private BusinessServiceImpl instance;
public BusinessService getInstance() {
// instance creation logic, same as singleton creation logic
}
}
Use an enum to deal with the singleton logic. Remove the getInstance()
method from your interface.
public enum BusinessServiceImpl implements BusinessService {
INSTANCE;
// implement the methods from your interface
}