Singleton Design Pattern mode belong to the simplest of a pattern, in practical applications is very wide, but may be affected by various types of tutorial and saw that a lot of implementation are still used in Java, in fact, be in .NET more concise implementation.
First, knowledge presentation
The core objective: To call throughout the project are the same instance of an object in order to achieve resource sharing. Such as environment variables.
Common ways: starving mode, lazy mode, dual-mode lock
Second, implementation
/// <Summary> /// starving mode, every time it loads a waste of resources /// </ Summary> public class EagerSingleton { public static Demo Instance { GET ;} = new new Demo (); }
/// <Summary> /// lazy mode for simple applications no multithreaded /// </ Summary> public class LazySingleton { Private static Demo _instance = null ; public static Demo Instance { GET { IF (== _instance null ) _instance = new new Demo (); return _instance; } } }
/// <summary> /// 线程安全 /// </summary> public class ThreadSafeSingleton { private static Demo _instance = null; private static readonly object _lock = new object(); public static Demo Instance { get { if (_instance == null) { lock (_lock) { if (_instance == null) _instance = new Demo(); } } return _instance; } } }
Called
static void the Main ( String [] args) { ThreadPool.SetMaxThreads ( 25 , 25 ); // adjust the maximum number of threads ThreadPool.SetMinThreads ( 10 , 10 ); // adjust the minimum number of threads Console.WriteLine ( " ================ ===== example: ========== starving multithreaded mode " ); the Parallel.For ( 0 , 10 , (I) => { Console.WriteLine ($ " {EagerSingleton.Instance } .id " ); }); Console.WriteLine (); Console.WriteLine (" ========== Example: ========== lazy multithreaded mode " ); the Parallel.For ( 0 , 10 , (I) => { Console.WriteLine ($ " {} LazySingleton.Instance.Id " ); }); Console.WriteLine (); Console.WriteLine ( " ========== example: multi-threaded thread safe mode ======= === " ); the Parallel.For ( 0 , 10 , (I) => { Console.WriteLine ($ " {} ThreadSafeSingleton.Instance.Id " ); }); the Console.ReadKey (); } public class Demo { public string Id { get; private set; } public Demo() { Id = Guid.NewGuid().ToString(); } }
Result of the call:
CONCLUSIONS
> Starving mode is suitable for small-scale and multi-threaded applications involved, but to focus on resource consumption singleton object.
> Lazy mode does not need to apply to multi-threaded applications, easy to understand and remember the results were pretty good.
> Double lock mode to apply to relatively standardized application for systematic long-term planning.
> Do not implement singleton pattern ICloneable interfaces, do not involve serialization, otherwise there will be multiple objects.