Three implementations of Singleton -- C #
Traditional double check:
public sealed class Singleton{ private static Singleton instance = null; private static readonly object padlock = new object(); Singleton() { } public static Singleton Instance { get { if (instance == null) { lock (padlock) { if (instance == null) { instance = new Singleton(); } } } return instance; } }}
Defects:
1. The code is bloated.
2. The performance of double check is slightly lower (compared with the subsequent implementation version)
Version that utilizes the. net framework static feature:
public sealed class Singleton{ public static readonly Singleton instance = new Singleton(); private Singleton() { }}
1. How to ensure the safety of singleton and thread?
Because the static instance only has one memory in the AppDomain
2. defects?
The static constructor is executed before the field, without lazy (the instance is used only)
Lazy version
public sealed class Singleton{ public static readonly Singleton instance = new Singleton(); // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static Singleton() { } private Singleton() { }}
Improvements:
Display the declared static constructor and tell the compiler to execute it after the field. This will be instantiated only when the field is used.