Singleton: Mostly Evil

05/21/11

Permalink 10:30:32 pm, by truewill Email , 219 words, 220 views   English (US)
Categories: C#, IoC, .NET, Design

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…

Comments, Pingbacks:

No Comments/Pingbacks for this post yet...

Leave a comment:

Your email address will not be displayed on this site.
Your URL will be displayed.

Allowed XHTML tags: <p, ul, ol, li, dl, dt, dd, address, blockquote, ins, del, span, bdo, br, em, strong, dfn, code, samp, kdb, var, cite, abbr, acronym, q, sub, sup, tt, i, b, big, small>
(Line breaks become <br />)
(Set cookies for name, email and url)
(Allow users to contact you through a message form (your email will NOT be displayed.))
The name truewill is composed of two other words. What is the SECOND word?

Development Central

Development Central is the blog of Bill Sorensen, a professional software developer. Much of this will relate to C#, .NET, and OOP in general.

Disclaimer
These postings are provided "AS IS" with no warranties and confer no rights.

Search

Categories

Linkblog

b2evolution

contributors

XML Feeds

What is RSS?

Who's Online?

  • Guest Users: 3

powered by b2evolution free blog software