简体   繁体   中英

Static constructor in Singleton design pattern

On MSDN I found two approaches to creating a singleton class:

public class Singleton {
   private static Singleton instance;
   private Singleton() {}
   public static Singleton Instance {
      get {
         if (instance == null)
            instance = new Singleton();
         return instance;
      }
   }
}

and

 public sealed class Singleton {
   private static readonly Singleton instance = new Singleton();
   private Singleton(){}
   public static Singleton Instance {
      get { return instance; }
   }
}

My question is: can we just use a static constructor that will make for us this object before first use?

Can you use the static constructor, sure. I don't know why you'd want to use it over just using the second example you've shown, but you certainly could. It would be functionally identical to your second example, but just requiring more typing to get there.

Note that your first example cannot be safely used if the property is accessed from multiple threads, while the second is safe. Your first example would need to use a lock or other synchronization mechanism to prevent the possibility of multiple instances being created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM