ALLINSIGHT

Home of the AlmostImplementedException

Singleton evil or not?

Its not in the genes its the environment! <==> They are not evil just misunderstood.
Yeah, ok you get it 😀

Singletons are a very special type of objects and should be treated like that. There is no general pattern to implement and no keyword to identify them. So what the heck is a singleton?

A Singleton is like the Highlander: “There can only be one”. So if you use a singleton-class only one instance can exist and this instance is used everywhere throughout the entire application.
To implement a singleton you have nothing else to do then hiding the constructor with protected (not private! thats evil) to provent instantiation and then provide a method to get an instance which is returning always the same. And the problems start right there.

First of all be sure you just want only a single instance for the rest of the applications life.
Second be sure you implemented it right, you don’t want multiple Highlanders kill each other.
And third, keep your head where it belongs in choosing the right singleton pattern.

First i thought i should post the evil-implementations that you can find throughout the internet and discuss them, but i thought this could be confusing. So we do it the other way around. The code above is a “good” singleton pattern. You should use it, if you need a singleton.

Why is it good?
First of all I didn’t use private. If you use private, nobody can extend your singleton. Think about when you want to test your code and need a mock-object to replace your singleton. When you declare the instance-variable as private, there is no way to replace it.
Second, I used an interface to define the methods the singleton provides. This way you can set the instance-variable with another implementation (for testing).
Third, the getter creates a new instance just when it is needed and this way you can override it before the getter is called and it would return this implementation instead of creating a new one.

With protected and an interface the following is possible:

Since SetInstance sets the instance-variable, the getter would return the fake-instance and everything is fine. And thats all you need to know about singletons.

To see all the evil-implementations just google for Singleton .NET evil

Share :

One thought on “Singleton evil or not?

Leave a Reply

Your email address will not be published. Required fields are marked *