Singletons are a bad idea for the most part. I believe everyone is on board with this concept. I am wondering why does Angular rely so heavily on factories for its dependency injection considering factories are singleons ? Why are singletons not a bad idea in Angular ?
Asked
Active
Viewed 163 times
1
-
"Singletons are a bad idea for the most part." Not necessarily? – TonalLynx Dec 16 '15 at 22:22
-
2Counter-question: Why do you think singletons are a bad idea? Personally I quite like them. – HankScorpio Dec 16 '15 at 22:25
-
@HankScorpio http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons – TkNeo Dec 16 '15 at 22:33
-
@TonalLynx http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons – TkNeo Dec 16 '15 at 22:33
-
Basically, you want to search for IoC. Singletons are pretty often used in systems using it (consider Spring in java for example). It's all about ability to swap implementations, not about how many instances you have. – fracz Dec 16 '15 at 22:56
1 Answers
4
Singleton is not considered a 'good practice' when accessed directly, through global class name (in java) or as a global variable. Your code is coupled with it and difficult to reuse and unit test. Changes in one class/module can cause a side effect in another one without you being able to execute those modules independently.
In Angular
it is injected as a dependency - a function parameter. So it is a different thing. You can easily pass different implementation of you singleton to one function and different to another (if you wanted). Your code explicitly declares it as dependency and allows the client (caller) to pass whatever he wants instead of hiding it internally.

jonasnas
- 3,540
- 1
- 23
- 32