Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we seal Singletons? Should we try to inherit from Singletons in the first place?

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

like image 892
devoured elysium Avatar asked Apr 04 '10 03:04

devoured elysium


People also ask

Why should singletons be sealed?

Marking the class sealed prevents someone from trivially working around your carefully-constructed singleton class because it keeps someone from inheriting from the class.

Can you inherit from a singleton?

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.

What is the best way to subclass singletons?

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.

What we can do in singleton class to avoid inheritance?

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.


1 Answers

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.

like image 104
Aaronaught Avatar answered Oct 31 '22 17:10

Aaronaught