3 ms·
IMHO, like most patterns, the pattern is appropriate in some situations and not always an anti-pattern. It only becomes an anti-pattern when it is abused in sit
by vkjv 12y ago
IMHO, like most patterns, the pattern is appropriate in some situations and not always an anti-pattern. It only becomes an anti-pattern when it is abused in situations where it is not appropriate.
For example, how would you go about implementing a connection pool without a singleton? Even if you pass it around everywhere, it's still a singleton, just explicit instead of implicit.
- chris_wot 12y agoWhat if you have two types of connection pools?
- nsxwolf 12y agoThen you have a singleton containing singleton pools.
- dpark 12y agoThe problem (at least one of the biggest problems) with singletons is exactly that the singleton state is explicit. Making a singleton explicit means making it global, which allows random code all over the place to take direct dependencies on it. This increases coupling, and also makes it hell when you realize you were wrong and you need two instances of the singleton. To your example of the connection pool, there is absolutely no reason that this has to be a singleton. You could have N connection pools, each with their own pool of connections, just as you could have N thread pools, or N memory heaps. This is not only possible but sometimes preferable, if different subcomponents need resource isolation (so that some connection-hungry component can't starve a component that needs reasonable responsiveness for the interface, for example). Further, most of your code shouldn't even care about the connection pool. That's a level of coupling you generally do not need. Most code should care only about an actual connection, which could be passed in. Taking a direct dependency on the connection pool when not necessary increases pointless coupling and makes changes more expensive.
- TheCoelacanth 12y agoA class that happens to only ever be instantiated once is not automatically a singleton. It is only a singleton if it takes steps to ensure that it can never be instantiated more than once. I don't see any reason that a connection pool would have to make sure that there are no other connection pools in the application.