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 ?
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.