Reputation: 857
I have seen lot of "singletons are evil" in this site. It almost make me believe singletons are pathological liars. But, If it's true, why there are so many singletons in cocoa? Like shareApplication, shareManager, and more. And I'm wonder that if I don't use singleton pattern, how can I do the same things like it. For example, ensure there is only one instance and access it when i need.
So I will doubt the saying until I can figure out there is a better way.
Please help me. Thanks
Upvotes: 3
Views: 349
Reputation: 4428
There is no a single feature or pattern that is inherently evil. Even goto
has its use and can sometimes improve readability. "Singletons are evil" comes from the fact that many novice developers are prone to misuse of them. So this is a common sense and sometimes common sense isn't the best solution.
In your examples shared...
are not technically singletons. You can create thousands instances of UIApplication
or NSFileManager
at the same time. They are more like service locators ("find me my application", "find me a default file manager"). These methods provide us with some useful shared values we need 99% of time. Though this can make unit testing harder benefits are worth it.
Upvotes: 3
Reputation: 24439
There are so many singletons in Cocoa because it was designed long before it was cool to declare “evil” and “considered harmful” on everything one had problems with.
Singletons are not totally evil. They work pretty well in many situations when used right. You've found out about the problems associated with them, but it does not mean you have to get rid of them immediately otherwise the world will end. The realities of some projects are such so you won't ever experience problems of singletons.
Obviously you can't avoid using library singletons when they already exist. Whenever you need a certain object like NSApplication or NSWorkspace, you should use their sharedApplication/sharedWorkspace methods, that's how system frameworks were designed.
When designing your own code, instead of singletons you can make sure that objects are only created by factories, and code some factory methods in a way so that they return previous instance if this kind of object was requested before. This design avoids typical disadvantage of globals and singletons of being unable to substitute mocks instead of them.
Upvotes: 0
Reputation: 7573
Singletons are generally helpful to store your global data on.
However Singletons are usually just used as a junkyard for all kinds of random methods and variables without any order or reason.
http://blogs.msdn.com/b/scottdensmore/archive/2004/05/25/140827.aspx
This is probably why people dislike the use of them Singletons.
If you don't misuse the Singleton with chaotic behavior then you shouldn't avoid using it in my opinion.
Upvotes: 0