Usually you wouldn't extend a Singleton class. In fact, usually a Singleton class would be designed in a way to prevent it being extended, in case extending it was used as a way to create multiple instances.
Matthew Brown wrote:Usually you wouldn't extend a Singleton class. In fact, usually a Singleton class would be designed in a way to prevent it being extended, in case extending it was used as a way to create multiple instances.
I think that the definition of a Singleton as having only one instance is misleading: better say that only one combination of values (object "state") is involved in methods implementation.
So curiously you can create a Singleton that is implemented without the calling code being aware of this property: the different instances created by client code all delegate to a single object!
and yes you can create subclasses of this façade.
Joined: Jun 18, 2009
Thanks for your responses.
I still didnt get a concrete answer about whether we can Extend a Singleton Class or not.
you can attempt to do it the exact same way you'd extend any other class...however, depending on how the singleton is written it may not actually work. It is impossible to say without knowing more about the specific singleton implementation you are trying to extend, which clearly we don't have. But all you'd do is
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
All you need to extend a singleton class is a constructor with protected or package-default in the singleton class. If there are only private constructors you simply won't be able to extend it. If there are public constructors then it's not a singleton class.
Note that to use a package-default constructor your class needs to be in the same package as the singleton class; visibility of constructors is no different than the visibility of methods or fields.
Just for sake of my own interest, may I ask you why are looking to extend Singlton class Or where you got this requiremtn from ?
What i understand is Singlton is just a concept that one instance per JVM (or per App in case of App servers like WLS).
you can implement this using different ways,
the most common way I have seen is making Contructior private and providing Factory method to control Instantiation: in this case definitely Extends would never work since constructor is private.
I would be happy to see the Singlton implimentation you have in your mind which allows the Extension (I mean Extends), may be i would learn something more
“The difference between 'involvement' and 'commitment' is like an eggs-and-ham breakfast: the chicken was 'involved' - the pig was 'committed'.”
Joined: Mar 03, 2008
Pat Farrell wrote:Singletons are evil and should be avoided.
can you please elaborate on this please? Since actually I found them quite handy sometimes