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:
- Type initialization is lazy.
- Type initialization is thread-safe.
- 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?