mercredi 4 mars 2020

Why Singleton Lasy Instantiation over Static Initialisation Or Multi-threaded Instantiation? C#

I read here https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ff650316(v=pandp.10)?redirectedfrom=MSDN about 3 different ways of implementing the singleton in c#. I'm particularly interested in understanding this line:

Because the instance is created inside the Instance property method, the class can exercise additional functionality (for example, instantiating a subclass), even though it may introduce unwelcome dependencies.

I understand that although lazy instantiation is not thread safe, still because it only instantiates it on demand it thus avoids instantiation every time the class is loaded. But say I didn't mind it's instantiated every time it's loaded, why would I choose this over static or even over the multi-threaded approach? Is there something Lazy can get me that static and multi-threaded can't? Can one be subclassed and the other not?

Whilst I'm at it:

Consider the following two pairs of examples of Lazy vs Static, my question is, within each pair, how are they different from one another?

 public class LazySingleton
    {
        private static LazySingleton _LSInstance;

        private LazySingleton() { }

        public  static LazySingleton GetInstnace 
        {
            get{

            if (_LSInstance == null)
            {
                _LSInstance = new LazySingleton();

            }

            return _LSInstance;
            }
        }
    }

    public class LazySingleton
    {

        private static LazySingleton _LSInstance { get; set; } 

        private LazySingleton() {   }

        public  static LazySingleton GetInstnace() {  

            if (_LSInstance == null)

                _LSInstance = new LazySingleton();

            return _LSInstance;

        }
    }

=======================================================

 public class Singleton
    {


        private    Singleton()
        {

        }

        private static Singleton _LSInstance = new Singleton();


        public static  Singleton GetInstnace 
        {
            get{ 

            return _LSInstance;
               }
        }
    }

public class Singleton
  {


      private    Singleton()     {    }

      private static Singleton _LSInstance = new Singleton();


      public static  Singleton GetInstnace()
      {

          return _LSInstance;

      }
  }

I'd really appreciate a response that can clarify this for me, thank you!

Aucun commentaire:

Enregistrer un commentaire