Well from your post, even if it's not clearly stated, sounds like you want the abstract class to play two different roles.
The roles are :
- the abstract factory role for a
(singleton) service that can have
multiple substitutable
implementations,
- the service
interface role,
plus you want the service to be singleton enforce 'singletoness' in the entire family of classes, for some reason it's not enough for you to cache the service instance.
This is fine.
Somebody will say it smells very bad because "violates separation of concerns" and "singletons and unit testing don't go well together".
Someone else will say it's ok-ish because you give put responsibility of instantiating the right children in the family itself and also expose more fluent interface overall since you don't need mediation of a factory that does nothing else than exposing a static method.
What is wrong is that after you want the children to be responsible of selecting what implementation should the parent factory method return.
It's wrong in terms of design because you are delegating to all children what can be simply pushed up and centralized into the abstract superclass and also it shows you are mixing together patterns that are used in different contexts, Abstract Factory (parent decide what family of classes clients are going to get) and Factory Method (children factories select what the clients will get).
Factory Method is not just not required but also not possible with factory methods since it is centered on implementing or overriding "instance" methods. There is no such thing as override for a static methods, nor for a constructor.
So going back to the initial good or bad idea of an abstract singleton that selects which behaviour to expose there are several ways to solve the initial problem,
One could be the following, looks bad but i guess is near to what you were looking for:
public abstract class A{
public static A getInstance(){
if (...)
return B.getInstance();
return C.getInstance();
}
public abstract void doSomething();
public abstract void doSomethingElse();
}
public class B extends A{
private static B instance=new B();
private B(){
}
public static B getInstance(){
return instance;
}
public void doSomething(){
...
}
...
}
//do similarly for class C
The parent could also use reflection.
More test friendly and extension friendly solution is simply to have children that are not singleton but packaged into some internal package that you will document as "private" and abstract parent that can expose the "singleton mimiking" static getInstance() and will cache the children instances enforcing that clients always get the same service instance.