Lately there have been some kind of revolution against singletons, but is there something wrong with them if they are stateless?
I know the overuse talk and all... this applies to everything not just singletons.
|show 7 more comments|
For more details see the-onion-architecture
It always depends on the usage.
I think the revolution comes from the fact, that every programmer learns this pattern as the object oriented pattern. Most forget to think about where it makes sense and where it doesn't.
If you have a stateless singleton, why not use a class offering only static methods (or use a static class)?
Here some post regarding global variables and singletons in general.
I wouldn't be as strict as the author but he shows that for most cases where you think you need a singleton, you don't really need it.
|show 6 more comments|
There is nothing an immutable stateless singleton can do that a static class can't.
There is simply no reason to add the extra level of complexity that ->Instance() creates, while plain call to a static method will be clearer, more conservative in terms of resources and probably faster.
It's not that they are wrong. It's that there is a better way to do it. There are scenarios where normal ("stateful") singletons are the right way to go. The evil with singleton is that they are often abused, with same bad results as global variables, but there are specific cases where using a singleton is simply correct. There are none such cases for the stateless ones.
|show 3 more comments|
The main problem with singleton is that it hides dependecies and coupling expecially when used in cross-cutting concerns scenario. See Singletons are Pathological Liars or Why Singletons are Evil for further reading.
From the other side, a state less singleton, if not abused, may be helpful and improve performance. Consider an example:
Here, the StatelessSingleton acts as default implementation of the Interface and is put into the User constructor. There is no hard-coded coupling and hiden dependencies. We are unable to use a static class due to the underlying interface but there is no reason to create more than one instance of a default. That's why a stateless singleton seems to be an appropriate choice.
However, maybe we should use another pattern for a default implementation:
It hits the performance with respect to StatelessSingleton but constitutes a generic implementation of the Interface. Similar solution is used by IProgress interface.
Altough again, why allow to create more than one implementation of default behaviour? Yet we can combine the two:
In conclusion, I believe that there are places (as depicted defaults) where Singletons are useful. The main definition of Singleton states that it disallow to create more than one instance of a class. It's as nuclear power. Can produce an energy or a bomb. It depends on human.