Why are singletons considered to be a bad practice?
Duplicate:
What is so bad about Singletons?
I was reading this question, and was surprised to see that (s)he considered a singleton to be considered a "bad practice," and in fact thought that this was common knowledge.
I've used singletons quite a bit in any project that uses iBatis to load the queries from XML. It great improves speed in these instances. I'm not sure why you wouldn't use them in a case like this.
So... why are they bad?
They are not necessarily bad, just misused and overused. People seem inexplicably attracted to the pattern and look for new and creative ways to shoehorn it into their application whether or not it really is applicable.
They're a tool, and like any tool there are times you should use them and times you should use something else. In this case, it's very often true that something else (Factory, static class) would be better in situations that at first glance may seem appropriate for a Singleton.
When Design Patterns
came out it seemed like everyone jumped on the Singleton bandwagon — they were everywhere, even places they shouldn't be. What you see now is a (perhaps well-deserved) backlash. Not that you shouldn't use them at all, but it might be a good idea to take a step back and look at all the options available.
Singletons are not bad practice at all. In fact they are extremely useful for many situations. But they do have two major areas ripe for abuse and/or failure:
Both can be handled, but beginners often neglect to do so (usually through ignorance) and it ends up causing far more trouble than they know how to deal with.
链接地址: http://www.djcxy.com/p/82158.html上一篇: C#
下一篇: 为什么单身人士被认为是不好的做法?