Singleton

xiaoxiao2021-03-06  36

Singleton is taken from: MSDN

///

/// Multi-threaded environment is unsecured /// Different threads in the execution process simultaneously enter instance /// then possible to create multiple Singleton object instances /// and decide must create new examples /// public class Singleton {private static Singleton instance; private Singleton () {} public static Singleton GetInstance () {if (null == instance) {instance = new Singleton ();} return instance;} }

Static Initialization ///

/// Static Instantiation // / Avoiding Multithreading Environments Are Not Safe /// Members of Unsecured /// First Reference Class When Create An Instance / / The Public Runner is responsible for processing variable initialization / // Block generation is prevented by SeaD, because derived may increase instance /// public sealed class singleton {private static readonly singleton instance = new singleleton () (); private singleton () {} public static singleleton getInstance () { Return Instance;}}

Or public sealed class Singleton {private static volatile Singleton instance; private static object syncRoot = new object (); private Singleton () {} public static Singleton GetInstance () {if (null == instance) {lock (syncRoot) {if ( NULL == instance) {instance = new singleton ();}}} Return Instance;

转载请注明原文地址:https://www.9cbs.com/read-58404.html

New Post(0)