I keep reading over and over again that one should avoid using singletons for various reasons. I’m wondering how to correctly handle a situation where a class represents a unique system resource. For example, a AudioOutput class using SDL. Since SDL_OpenAudio can only be open once at a time it makes no sense having more then one object of this type and it seems to me preventing accidentally making more then one object would actually be good.
Just wondering what experienced programmers think about this, am i missing another option ?
Using design patterns wisely is a tricky questions, and it requires a lot of practice.
I have seen a lot of people using Singleton just because it “sort of” fits what they need to do. And this often results in disasters, for example in case of multi-threaded environments, or just as it was meant to hide a design flaw and needed a complete system redesign later on.
I’d say you need to think about a few things when considering Singleton:
But I’d say don’t spend too much time on it: it may not be always the best solution, but this is still an acceptable solution in some cases, and unless you’re in a multi-threaded environment, you’ll probably rarely have issues. It’s mainly a design choice.
If you want to gain more knowledge about design patterns, I advise this book, which is pretty much the reference on the topic.