The most common way of implementing a singleton in java is to use a private constructor with a public accessor method of the form —
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static synchronized Singleton getInstance(){
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
However, since the constructor is private, it prevents subclassing the singleton. Is there any way in which we can make a singleton which allows subclassing ?
When you have a
class A extends B, an instance ofAessentially “includes” instance ofB. So the very concept of inheritance is contrary to the singleton model.Depending on what you need it for, I would consider using composition / delegation. (A would have a reference to the singleton, rather than extending its class). If you need inheritance for some reason, create an interface with the Singleton methods, have Singleton implement that interface, and then have another class also implement that interface, and delegate to the singleton for its implementation of the relevant methods.