Geeks With Blogs
New Things I Learned

The singleton pattern is pretty well known – the idea is to create a single instance of an object, and only use that particular instance forever.  The construct should disallow creation of additional objects, preferably through some language construct, rather than through using manually checking, or initializing a flag.  A typical example would be like the following:

public class MySingleton
{
   private MySingleton()
   {
   }

   private static MySingleton _instance = new MySingleton();
   public static MySingleton Instance
   {
      get { return _instance; }
   }
}

By using a private (or protected constructor, depending on what you prefer / want to do with the class), it somewhat  guarantees that no outside code can instantiate the class.  The framework will automatically instantiate the _instance field, and any reference from the outside has to use the public Instance property.  If you’re paranoid about people using Reflection to instantiate this class, then you can also put some code in the constructor to check – but if they can use reflection to begin with, any flag/value you want to check can be reset anyway, so it’s a moot point.

In my current project, we have quite a bit of Singleton classes – of course there’s the debate as to whether you’re better off using a Singleton pattern, or just use static classes.  I have my own views as to when/where you should use which construct, but that’s for another post.  And as simple as it is to make a class to be a Singleton, it irks me that I have to repeatedly type that _instance field / Instance property for all my singleton classes.  So I tried to see if I can create a base class for classes that needs to be a Singleton.  This is the code result that I ended up with:

public abstract class Singleton<T>
   where T : Singleton<T>
{
   protected Singleton()
   {
   }

   private static T _instance;
   public static T Instance
   {
      get { return _instance; }
   }

   static Singleton()
   {
      _instance = (T)Activator.CreateInstance(typeof(T), true);
   }
}

The first big problem is of course, the Instance property has to return the specific type – otherwise it won’t work.  So, we have to use generics; the generic constraint used in the code above is what is termed a Recursive Generics.  The link I provide here is the first returned result from Google search for it.  The first time I heard & saw this was from a presentation by Rockford Lhotka on his CSLA framework, way back in 2005 – I thought it was pretty mind-blowing that you can actually do this.  Anyway; the generic constraint basically only allows T to be classes that derive from this class itself.  From here on, creating my Singleton class is pretty automatic:

public class MySingleton : Singleton<MySingleton>
{
   private MySingleton()
   {
   }

   public void SomeMethod()
   {
      // Do stuff here
   }
}

The class declaration looks a tad weird (again because of the recursive generics), but essentially it specifies that MySingleton class derives from Singleton<T> class, and the generic type is the MySingleton class itself.  In the base class, T is now MySingleton and the static constructor will automatically fill the _instance field before any methods/fields/properties can be accessed from the MySingleton class; it uses the Activator class to create an instance of T, and it uses the CreateInstance overload that allows using private or protected constructor.

The Singleton class still need to declare either a private or a protected constructor – If there are no constructors, .NET will automatically assume the class has a public parameterless constructor, which means the class can be instantiated by any outside code.  Calling the method does not differ from regular implementation:

private void Test()
{
   MySingleton.Instance.SomeMethod();
}

MySingleton class inherits the static Instance property from the base Singleton<T> class; and since that property returns MySingleton, then all instance methods/properties are available to consume.  Hope this can be of use…

Posted on Friday, July 24, 2009 8:11 AM | Back to top


Comments on this post: Base class for Singleton Pattern with Generics

# re: Base class for Singleton Pattern with Generics
Requesting Gravatar...
Is this singleton thread safe?

Can it instantiate Interface?
Left by Andreja on Mar 19, 2010 12:33 AM

Your comment:
 (will show your gravatar)


Copyright © Muljadi Budiman | Powered by: GeeksWithBlogs.net