C # design mode-Singleton,

Source: Internet
Author: User

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 ;}}}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.