C # design mode-Singleton,
Singleton mode is one of the simplest forms of design patterns. This mode aims to make an object of A Class A unique instance in the system. For some classes in the system, it is very important to have only one instance. For example, a system may have multiple print tasks, but only one job is in progress; A system can have only one window manager or file system. A system can have only one timing tool or ID (serial number) generator.
Obviously, the singleton mode has three key points. One is that a class can only have one instance; the other is that it must create the instance on its own; and the third is that it must provide the instance to the entire system on its own. From a specific implementation perspective, there are three points: first, the class in singleton mode only provides private constructors, and second, the class definition contains a static private object of this class, third, this class provides a static public function to create or obtain its own static private object. C # There are many methods to implement the singleton class. For details, see http://csharpindepth.com/articles/general/singleton.aspx#unsafe. the following two examples are available:
Method 1 (recommended ):
Class SingleOne {static SingleOne m_Instance = null; static SingleOne () {m_Instance = new SingleOne ();} private SingleOne () {// code: other constructors need to process code} public static SingleOne Instance {get {return m_Instance ;}}}
Method 2:
Public class SingleOne {static SingleOne m_Instance = null; private static readonly object obj4Lock = new object (); private SingleOne () {// code: other constructors need to process code} public static SingleOne Instance {get {if (m_Instance = null) {lock (obj4Lock) {if (m_Instance = null) {m_Instance = new SingleOne () ;}} return m_Instance ;}}}