This is a fairly common, and very, very useful pattern when that implemented properly. Implemented badly however can and most probably will kill your application, or at the very least cause some very perculiar behaviour.
I have no intention of re-inventing the wheel, many better than me have detailed how to create a singleton, one very good post can be found at this link. If your not sure i recommend you read the post (and i mean read it!!!).
Please people pay attention to the very important idea of thread safety, its really very easy (esspecially in a distributed system) to get threading issues without the correct use of a singlton, and by its very definition a singleton is threadsafe (only one instance can exist). So for those of you out there that seem happy with a static class for instance, yes this does have its place, and under the right conditions the right choice, but it IS NOT a singleton, don't lable it as one, don't rely on it as one, and if your building anything more complicated than what my cat can manage, i would recommend you think..."Should i use a singleton here?"
Sorry for the rant, but i've fixed far too many odd bugs this week caused by singletons that just aren't singletons...
No comments:
Post a Comment