Reputation: 5175
A comment at one of my other questions got me thinking. Right now I am using a singleton Session
. It's an encapsulation of a constant TCP connection to my server. It should connect on application launch, and stay connected during the whole lifetime of the application. I only need 1 (it makes no sense to have multiple connections to my server from the same app). And it should be globally accessible.
Is it bad design to use a singleton for this kind of object?
Upvotes: 1
Views: 294
Reputation: 11038
No, the singleton pattern sounds quite good for this application. I have a similar situation in an app of mine, with a class that manages an instance of iAd
. I don't want to load ads over and over again, depending on the window; I just want to shuffle it around.
Similarly, you have a session that you want to maintain; the alternative to a singleton is to initialize it in the AppDelegate
and access it from around the app. This is functionally equivalent to the singleton pattern, but far clunkier, as you're really just piggybacking on a class you know will stick around.
Upvotes: 2
Reputation: 20236
If there can never be more than 1, and it needs to be globally available, then the singleton pattern does make sense here. However, this information was left out of your previous question, which is why I commented on it the way I did.
Far too many people lean on singletons to solve problems easily rather than finding real solutions to the problem. In this case, I'll draw a parallel with the UIScreen
or UIDevice
on iOS devices:
UIScreen has a mainScreen
singleton, which refers to the screen on your iPhone, iPad, whatever. There can only ever be one main screen on these devices.
Conversely, UIDevice has a currentDevice
class method which achieves the same purpose: There can only be one device.
Upvotes: 2