Monday, March 31, 2008

Generic Singleton Risks

The Singleton pattern is very well known to .Net developers, especially the static implementation.
Lately I have encountered several versions of the generic Singleton, among them the one described in Arnon's post.

However, there is one possible pitfall to this approach, as it makes this code possible:
Singleton<myclass> obj = Singleton<myclass>.Instance;
MyClass obj2 = new MyClass();

While I personally like the idea of having the freedom to use the same class in two different ways throughout the application, I know some people like their Singletons - well, single.
On the other hand, if you write a class from the start as a Singleton this is not an issue.

There is an inherit risk in decoupling a class from it's expected behavior, so take this into consideration before using this pattern.

No comments: