Reputation: 1692
Not quite sure whether this has been asked before.
Language is c++. I am writing a class with a number of data items that should have a static behavior, say a buffer of 1 KB that holds some data and should be shared for all objects. My boss ask me, why don't you write a singleton class and put all the data items inside it?
I have some bitter experiences with singleton and also recently I have googled "singleton is evil" and read a couple of articles. In SO also I read the same. So I was a little hesitant to use singleton in the above case, because I believe it is not really required there. So I asked my boss, will it be OK to have static data members for the required data items, instead of making the class singleton? But he is not giving me any clear answer and tells me, design patterns are there to make life easier, so what is the problem in using it. I don't want to argue with him. :)
I am not an OOP expert. So it will be helpful if somebody can comment on whose point make more sense [also whether both are wrong :)].
Thanks...
Upvotes: 0
Views: 138
Reputation: 8774
A singleton is essentially nothing but some OO encapsulation around a global variable.
If you encapsulate your state in some class and just add that as a static member to the class that needs the info, you're not really doing much different from a singleton, just with at least two drawbacks:
Sure, Just slapping a bit of Singleton Magic on top of globals doesn't make the problems with global state go away, and in that sense, singletons are evil™. But there are cases where your model needs to have global state. Encapsulation is a good thing in those instances, since it allows you to control who modifies what, when, and how. You can make the singleton factory method only accessible to certain classes, for example.
Upvotes: 2