I have seen some people in SO commenting that Singleton Pattern is an anti-pattern. I want to know why ?
I have seen some people in SO commenting that Singleton Pattern is an anti-pattern.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Testing
One reason is that singletons aren’t easy to handle with unit tests. You can’t control the instantiation and by their very nature may retain state across invocations.
For that reason the principle of dependency injection is popular. Each class is injected (configured) with the classes they need to function (rather than derive via singleton accessors) and so tests can control which dependent class instances to use (and provide mocks if required).
Frameworks such as Spring will control the lifecycle of their objects and often create singletons, but these objects are injected into their dependent objects by the framework. Thus the codebase itself doesn’t treat the objects as singletons.
e.g. rather than this (for example)
you would inject the calculator:
Thus the
Portfolioobject doesn’t know/care about how many instances of theCalculatorexist. Tests can inject a dummyCalculatorthat make testing easy.Concurrency
By limiting yourself to one instance of an object, the options for threading are limited. Access to the singleton object may have to be guarded (e.g. via synchronisation). If you can maintain multiple instances of those objects, then you can tailor then number of instances to the threads you have running, and increase the concurrent capabilities of your codebase.