Hello all
i need to create several single tones , and i like to make the class that have to be singleton just to inherit or implement some kind base class
and then it will become singletone .
how can i do that ?
I think it is not possible because for singleton class you will be declaring constructor as private which will stop you from overriding the class.
But i would like to know the answer if you find any.
Its really difficult to create a base class for singletons, since the most important method in the singleton is this one:
and since it is static you can't define it as abstract and force the user to define it. so the instance() method could not be put in an abstract class nor in an interface.
You can always call a public abstract method from inside your private constructor to do the custom initialization stuff. Something like
private MySingleton(){
//Do base/common intializing stuff here
customInitialize(); //this is an abstract method in your base abstract class
}
and how can you call this method from the outside ? you never initialize a singleton using its constructor, you have to call the static getInstance() method on its class.
Maneesh Godbole wrote:You can always call a public abstract method from inside your private constructor to do the custom initialization stuff.
But if you only have a private constructor, you cannot override the class.
If a singleton class needs to be overridden, you will need to make the constructor protected, or at least not private (default access may be just fine). However, that does allow sub classes to call the constructor, and there is nothing preventing sub classes from making their own constructors public, effectively making it a non-singleton class.
The only way I can think of to enforce sub classes to be singleton classes as well is to keep track of whether or not a class is already instantiated. The constructor of the base can then keep that list up to date:
(synchronization omitted for simplicity)
It doesn't enforce classes to be a true singleton though - it's still possible to create one single instance through a public constructor. After that there will be no more instances though.