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:
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?
Readability
This is how your code would look like when implemented with Lazy<T>
:
class DataModel
{
private static readonly Lazy<XmlSerializer> lazySerializer =
new Lazy<XmlSerializer>(() => new XmlSerializer(typeof(DataModel)));
public static XmlSerializer Serializer
{
get { return lazySerializer.Value; }
}
}
Lazy<T>
's documentation suffices),Lazy<T>
is much more expressive. It is immediately clear that the value utilizes deferred initialization.
For example I use it in situations when the intialization of some resource is too heavy to put in the constructor and I don't want the API-consumer to call some explicit Initialize routine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With