- When your domain specifies that there only exists one unique instance of something you're modelling
I still believe singletons should be avoided (in Java at least).
There's two different things to consider: the concept and the mechanism for enforcing the Singleton pattern.
The concept of Singletons have many uses, logging, configuration, not to mention when the domain you're working actually has things where there is ever only one instance of them and you wish to model that. I.e. a company only has a single expenses processing office and sending expense forms to an invalid office is wrong, the office is in reality a singleton. The concept of a singleton has many legitimate uses.
However, it's usually the mechanism that causes the problem. In Java we enforce an object can't be constructed by declaring the constructor private
, the problem with this is we also have to provide a global point of access to the instance through the concrete class. This couples everything in your application to that concrete class, which can't be changed at run-time, or mocked in unit testing. It's this mechanism which is considered evil - particularly in terms of testability.
If the concept of Singletons can be separated from the poor mechanisms, they would not be so evil. One example, I can think of is the @Singleton
scope available in Guice. In the context of Guice, it guarantees one instance, but it doesn't achieve this with the evil private constructor/global point of access mechanism.