Why use Lazy <T> instead of the static factory class for single player games?

Before I found the type Lazy<T>, I used the following template to implement 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 template provides the following benefits:

  • Type initialization is lazy.
  • Type initialization is thread safe.
  • Singleton access is simply direct access to fields without method calls.

Recently, I came across a lot of messages offering Lazy<T>to implement similar patterns of access to a single-user system. Is there any benefit from Lazy<T>(or LazyInitializer) for this implementation?

+4
source share
2 answers

readability

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; }
    }
}
+8

Lazy<T> . , .

, , - , , API- .

+2

Source: https://habr.com/ru/post/1685736/


All Articles