Single-Instance mode net

Source: Internet
Author: User

The recent use of a singleton mode, the following is a personal understanding, if there is no wrong, please all the way the big God pointing

1. Introduction: The singleton pattern strictly defines a class with only one instance and provides one of his global access points.

2. Problem solving: Singleton mode is required when a class simply requires that an instance can be created.

3. Composition: consists of a private variable, a private constructor, and a public method.

4. Example:

public class Singleton {//<summary>////programs to create a static read-only process helper object///</summary> Private stat    IC ReadOnly Object _object=new object ();            <summary>///construction method Private, foreign keys cannot instantiate this class through the new class//</summary> private static Singleton instance;        Private constructor Method Singleton (), you cannot use the New keyword to create an instance of this class. Private Singleton () {}//<summary>////This method is the only global access point for this class of instances//(double lock double-check Locking)///&L t;/summary>//<returns></returns> public static Singleton getinstance () {//First sentence If a broken instance is present, there is no more lock processing if (instance==null) {////The part of the program with the lock at the same time only one thread can enter, loc                    K (_object) {//If the instance does not exist, then new instance is returned, otherwise an existing instance if (Instance==null)                    {instance = new Singleton (); }}} return INstance; }} Client call: Class Program {static void Main (string[] args) {var singleton1 = Singleton.get            Instance ();            var singleton2 = singleton.getinstance ();            if (Singleton1==singleton2) {Console.WriteLine ("2 instances of the same");        } console.readkey (); }    }

  

Single-Instance mode net

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.