Why use Lazy<T> instead of static factory class for singletons?

Viewed 2289

Before I found the Lazy<T> type, I was using the following pattern for implementing global singletons:

class DataModel
{
    public static XmlSerializer Serializer
    {
        get { return SerializerFactory.instance; }
    }

    static class SerializerFactory
    {
        internal static readonly XmlSerializer instance =
            new XmlSerializer(typeof(DataModel));
    }    
}

This pattern provides the following advantages:

  1. Type initialization is lazy.
  2. Type initialization is thread-safe.
  3. Singleton access is simply a direct field access with no method calls.

Recently I've come across a lot of posts suggesting Lazy<T> for implementing similar singleton access patterns. Is there any benefit that Lazy<T> (or LazyInitializer) would bring to this implementation?

2 Answers
Related