Should a Singleton class be allowed to have children? Should we seal it? What are the pro's and con's?
For being able to inherit from a Singleton class, we would have to make the constructor protected instead of private. Now, that will be fine in c#, but the protected word in java gives both child-classes and package-classes access to the constructor. Which means not only classes that inherit from our Singleton can access the constructor but other classes in the same package can do it.
I'm a bit confused about all this facts. Maybe I am making a big fuss about nothing to worry about too much? Until now, I never had any necessity of trying to inherit from a Singleton, so maybe this is just an academic question!
Thanks
Marking the class sealed prevents someone from trivially working around your carefully-constructed singleton class because it keeps someone from inheriting from the class.
Unlike static classes, Singleton classes can be inherited, can have base class, can be serialized and can implement interfaces. You can implement Dispose method in your Singleton class. So, static classes are much less flexible compared to Singleton classes.
I would argue the most common way to implement a singleton is to use an enum with one instance. That might be a "better" way but definitely not the most common way. In all the projects I have worked on, Singletons are implemented as I have shown above.
Singletons usually have private constructor and possibly marked sealed , if it is so then you can't. If it is at least protected you can. If you just inherit from singleton class, result will not be singleton so you should follow the pattern and make it also singleton.
Yes, Singletons should be sealed. No, they should not be inherited.
The reason is that the primary (really only) behaviour of a Singleton is to create an instance of itself at some predetermined time. Since this functionality is static, it can't be overridden, so it would have to be duplicated instead. Once you start duplicating, you have multiple instances of a singleton, which doesn't really make sense.
Either that or you end up with race conditions or other conflicts as the "derived" singletons fight for control over the global instance, which not only doesn't make sense, it's dangerous.
There are some hackish workarounds to the Singleton inheritance problem, but that is what they are - hacks. The Singleton pattern is not really suitable for inheritance.
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