Why Singleton is anti-pattern? Why Singleton is Evil?
1. Testing
2. Singleton & Class Loaders
3. Violates Single Responsibly principle.
4. Represents Global State
1. Testing
A class using Singleton Object is hard to test because you cannot control that Singleton object used by the class. E.g. Singleton is DB Object. User has to initialize that object and he even cannot use different implementation (e.g. another Database).
2. Singleton & Class Loaders:
Singletons are not "single" per JVM or per application. It is singleton per class loader. That means if you have cluster (3 nodes) & each JVM (node) has 2 class loaders accessing the Singleton, there will be 3*2 = 6 singletons.
3. Single Responsibility Principle:
Because Singleton will take two responsibilties. One to control the instances, two to do the work that it is support to do (e.g. contain state, contain object, etc).
4. Why Global state is Evil?
What are the alternative?
1. Dependency Injection
2. Constants (Immutable global variables)
3. Immutable Singletons.
References:
1. http://programmers.stackexchange.com/questions/148108/why-is-global-state-so-evil
2.