If you want to create a class as a singleton which extends from another singleton, how would you go about it? You normally can't compile a class that extends from a class which has a private constructor. If this sounds like an idiotic thing to be doing in the first place, I'd welcome all opinons. Thanks. Paul
posted 13 years ago
Idiotic? No. Tricky? Yes. Create a separate package for you singletons. Give your constructor of the derived class private access. Do NOT specify any access modifier to your base singleton class. Give protected access to the static variable of the base class that represents your singleton instance.
At the end, your final singleton would ofcourse be an object of your derived class. Therefore, it raises some more questions that you'd have to workaround a little bit. Two problems with this approach - one thread may invoke Base.instance() whereas another may invoke Derived.instance(). 1) More than 1 Base objects are created. 2) you'd have concurreny issues. (ofcourse, concurreny issues exist even for the singleton creation logic - search in google). You can solve these problems by explicitly invoking Derived.instance() whenever your application is re-started. That should solve a lot of other problems. I haven't yet worked out all the cases - so if you find any glaring mistake, be liberal.