To begin with, I am NOT trying to create a subclass of a singleton class. (At least I'm sure I'm not trying to).
I have a class ClassA
that is abstract.
I have two classes, ClassA1
and ClassA2
that extend ClassA
.
I want ClassA1
and ClassA2
to be singleton classes. I could just write the code in each one to do so but I would prefer to write the code once in ClassA
and reuse it in all of it's sub-classes. Is there a way to do this?
Probably not - the singleton pattern requires static methods/fields, which would be shared by ClassA
and all its subclasses if defined in one place.
I would suggest private constructors for ClassA1
and A2 and having static methods for object creation. This way you have complete control over object creation.
The book EffectiveJava details out the adavatages of this approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With