开发者

Singleton.Instance = Lazy.Value?

Can we say making a class Lazy is like making it Singleton ?

In both case we create the instance via a property and access to the same instance (if i开发者_运维问答t's created) in further usages.


No, they are not the same.

Lazy initialisation of a variable only affects that variable, it doesn't make the class a singleton, or even reuse instances between variables. If you for example have two variables of the type Lazy<MyClass>, they would still create separate instances of the class.

A singleton usually uses lazy intialisation internally, but it doesn't have to. It could also be implemented using early initalisation, and just return the already created instance.


Your question is not clear, do you want a class in the singleton pattern with lazy initialization?

public sealed class Singleton
{
   private Singleton() { }
   static Lazy<Singleton> instance = new Lazy<Singleton>(() => new Singleton());

   public static Singleton Instance
      {
          get
          {
              return instance.Value;
          }
      }
}


No, you can have an object that is lazy but there can be multiple instances of the same object. Singleton would exist once and only once.


// This is a lazy class - but you can have more than one
class Lazy
{
    private int? _value;
    public int Value {
        get
        {
           return _value ?? (_value = new Random().Next()).Value;
        }
    }
}

you can of course make Value static so that all Lazys have the same Value

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜