Singleton: Mostly Evil

05/21/11

Singleton: Mostly Evil

I have upgraded the Singleton Pattern from Evil to Mostly Evil. Last week I actually found a valid use case for it.

I had a class that used the Strategy Pattern; a constructor parameter was an interface with a method for the algorithm. An IoC Container would have been overkill here; this was in a library module, and the class was only used by one other class in the library. That instantiated it twice, once for each of two algorithms (two strategies, each implementing the interface). The calling class had to know which algorithm to use each time.

The algorithms were pretty simple, and had no state. They were a little too complex for a lambda, though.

So I used Lazy<T> to make the strategies/algorithms Singletons, giving each a static Instance property that returned a lazy-created instance. (As an aside, if you make the constructor private you have to specify a lambda/delegate to Lazy or you’ll get a runtime exception.) I sealed the strategies to be safe.

If this seems like a very narrow use case to you, it does to me, too. But, if the stars align, you may be able to use the Singleton Pattern safely too. Hopefully without summoning the Great Old Ones*.

* - Some say Azathoth is itself a Singleton…


Your Host: webmaster@truewill.net
Copyright © 2000-2013 by William Sorensen. All rights reserved.