How do I inherit from a singleton class into other classes that need the same functionality? Would something like this make any sense?
There are several solutions that use inner classes and reflection (Some of them are mentioned in other answers). However I believe all these solutions involve a tight coupling between the clients and the derived classes.
Here is a way that allows the clients to depend only on the base class and is open for extension.
The base class is similar to the usual implementation, except we define it as an abstract class (If it is legitimate to instantiate the base class you can also define it like you would a regular singleton)
public abstract class Animal {
protected static Animal instance;
public static Animal theInstance(){
assert instance != null : "Cannot instantiate an abstract Animal";
return instance;
}
abstract void speak();
}
Any subtype would have its own theInstance method (you can't override a static method). For Example:
public class Dog extends Animal{
protected Dog(){}
public static Animal theInstance(){
if (instance == null){
instance = new Dog();
}
return instance;
}
@Override
void speak() {
System.out.println("Wouf");
}
}
In the main class you would write Dog.theInstance()
and any subsequent client would call Animal.theInstance()
. This way clients can be totally independent of the derived classes and you can add new subclasses without needing to recompile the clients (Open Closed Principle).