I was first introduced to the singleton pattern as an alternative to global variables (”global variables are bad, use a singleton instead”). But this is one instance where singletons emphatically should not be used. Replacing a global variable with a singleton is just a lazy way of avoiding global variables without avoiding any of the problems inherent in global variables.
He goes onto list the reasons not to use singletons this way which include (in my order of importance): difficult to test, inhibits code reuse, breaking modularity, inadvertent changes occur between accesses and multiple references.
A singleton is responsible for both its behaviour and for ensuring that only one instance of it exists. In other words, it is responsible for two unconnected activities. This should usually be avoided and the unconnected activities should be implemented in different classes.
No comments:
Post a Comment