Object Oriented Programming Patterns for Geeks

Singletons

I have always within myself wondered how much of a 'pattern' the Singleton is.  Ok, I suppose it is a 'repeatable solution to a common problem', which in this case is ensuring the existence of only 1 instance of an object exists at a time.  But singletons tend to be so common in OOP that they are almost bread and butter along with every other tenet - such as classes, inheritance, static members etc etc. 

However despite my view, they are accepted as a pattern and I am mildly surprised just how often this simplest of techniques is overlooked or not understood.  And conversely just how overused they can be when there may be a better solution (beyond subject of this text - type 'Singletons are Evil' into Google for more information).

Singletons are very useful so long as you use them correctly.  One of the biggest complaints about Singletons can be that they live for the lifetime of an application when this may not be the best thing.  There are times however when in certain contexts this is favourable and useful and so long as you use them correctly and keep in mind that this permanent state can be manipulated somewhat using other patterns. 

In respect to this I am supplying four basic Singleton examples each used for a specific purpose.  More complicated implementations of Singletons may or may not appear in later revisions on this site, these may or may not include techniques that include the use of .NET generics, abstract factories, providers, adapters and facades.  I'll see what the feedback brings me over time.

(NB: all my singleton examples assume a basic Multithreading knowledge, although this is not essential.)

The first and simplest Singleton and in my opinion potentially the worst is the 'SimpleSingleton'.  In .NET these work in an AppDomain global context and as such are of course available from everywhere within your applications AppDomain.  Just remember when using this one that global variables are seen as bad things in most scenarios.

The second singleton is a step up from the SimpleSingleton and allows individual thread based singleton contexts.  Unsurprisingly this is called the 'ThreadSingleton'.  This technique allows you to create and use Singletons based on the context of the thread a task is running on.

The third and fourth examples are useful in web development.

One of the big pains in developing websites can be the multiple places data can be stored and used.  If you ignore for a moment the obvious place that is the database or the awkward cookie standard this basically leaves in ASP.NET the Application and Session objects.  It is generally accepted that during the executable lifetime of a web application, any ‘global’ context data is stored in the Application object of the site. Any user data information is generally stored in the Session objects for data persistence between requests.  The big problem with this is that A. any data/objects stored in these areas are not strongly typed and B. it can become difficult over time to keep track of all the different keys used (and in fact I have yet to find a team that does know all of the keys).

Using a form of the Singleton pattern, it is possible to help resolve this.  Using Singletons it is possible to strongly type session/application stored data, and due to this it can help ensure that data keys are not inadvertently forgotten.

The ‘Web Application Singleton’ supplies you with a strongly typed Application data store, and due to the fact that it is a class, functionality can be tied to the data more directly – as per the OOP paradigm.

The ‘Web Session Singleton’ does a very similar thing to the ‘Web Application Singleton’, except of course it is used during session context.

The above two examples given are of course only small illustrations, but should give you a basic idea of what can be possible.

 



[3/23/2007] AndyJ: C# Singleton Patterns.

Here’s the implementation of a singleton I use which combines some nice generics and reflection:

public static class Singleton<T>
  where T : class
{
  static Singleton()
  {
  }
 
  public static readonly T Instance =
    typeof(T).InvokeMember(typeof(T).Name,
                           BindingFlags.CreateInstance |
                           BindingFlags.Instance |
                           BindingFlags.NonPublic,
                           null, null, null) as T;
}

 

I believe I originally dragged it up from this article:

http://www.codeproject.com/cs/design/GenericSingletonPattern.asp

 

It will only work with classes that have a private constructor with no parameters but it could be expanded to provide extra functionality.

It features a very compact design, encapsulation of the desired functionality leanly inside a single class and offers lazy instantiation.

[3/23/2007] Moridin8: re: AndyJ - C# Singleton Patterns.

Are you sure about the lazy instantiation part?

p.s.  nice to see you about again *g* wanna get involved with DATS?

[3/30/2007] Anon: Ref: Singletons

Putting the static constructor in the class means that the the class wont be marked with "beforefieldinit".

Because it is lacking this flag it will not have its type initializer invoked at any time before the first reference to a static field in it.

THis is all based on hearsay ;) I haven't bothered to test it out since my computer is dead at the mo, which also brings me around to my other point ... I'd love to work on DATS but unfortunatly it'll be a couple of months yet before I have a working dev machine at home again :(

[1/16/2008] Anon: Ref: Singletons

Another good example of a scoped singleton would be a HttpContext based singleton.  Typically in a web environment you'd use this rather than a ThreadStatic variable.

This means that you don't have to tidy the singleton down on the request ending.  Using ThreadStatic there is a risk of any state data being carried over to the next request.

Of course if your singleton is stateless then this is a non issue.