. NET Singleton mode ------- various writing methods & amp; Verification

Source: Internet
Author: User

Foreword The Singleton mode is no stranger to everyone, and it is easy to understand its principles. This article does not provide detailed analysis of Singleton mode, the purpose of this article is to demonstrate various implementation schemes (incomplete, but the most common method) of the single-sample mode in C # and verify its features (whether it is thread-safe, is initialization delayed ?), There are a lot of articles on the singleton writing mode, in various languages, but in many places it is only said: This mode supports multithreading, supports delayed initialization, and so on, there are many also provide why, next I will explain and verify the common Singleton mode solutions that everyone uses! If something is wrong, I hope I can get feedback from the distinguished readers. I think it is good. I would like to recommend it. Thank you. The simple principle is to resolve the singleton mode. The goal is to ensure that a class can only generate one instance and provide a global access point to obtain the instance. No matter which Singleton mode variant, you cannot leave the production step center. It seems that no matter which chicken claw shop, the method of making chicken claw is similar (you must first get the chicken claw, wash the Chicken claw, and get the chicken claw ). The Singleton mode is actually the same. The central steps include: restrict external new instances of this object and provide a unique object of this type internally, provides a global access point for the outside world to obtain the instance of this unique object for operation. In fact, this is simple. Next I want to analyze the singleton mode of four major variants and verify them separately. In preparation, I will provide you with a general framework for testing. You can continue without downloading it. The template provided by the test template download is very simple. There is only one class Person, and the following points are given: 1. the constructor is private (to avoid new instances ). 2. In the constructor, I wrote Console. WriteLine (mainly to observe when the class instance was initialized and how many times it was initialized ). 3. the static method getName () is used to call the getName method before obtaining the instance through the global access point. If the internal instance is not initialized, it indicates that the initialization is delayed, if yes, it indicates that initialization is not delayed. The following is an example. Copy the code public class Person {/* Hungry Chinese Singleton (thread security, delayed initialization not supported) * // The response is triggered during initialization and is applied to the validation of delayed initialization private Person () {Console. writeLine ("I initialized");} private static String name = "Jarvin"; // The only internal instance private static Person instance = new Person (); // Global Access Point, used to obtain the public static Person getInstance () {return instance;} // instance method public void Say () {Console. writeLine ("I am {0}", name);}/* static method, used for latency initialization verification * If the method has not been initialized before it is called, delayed initialization * such If the method is initialized before the method is called, The Initialization is not delayed */public static String getName () {return name ;}}. The method of copying the code test is as follows: 1. test whether Initialization is delayed: The test method is to call Person first. getName () to check whether the name is initialized before the result is returned. 2. Test thread security: three new multi-threaded tasks are enabled. The task content is to obtain the unique instance and call the instance method. The code for the Main method is as follows: copy the code class Program {static void Main (string [] args) {Console. writeLine (Person. getName (); Console. writeLine ("Enter multithreading mode below"); for (int I = 0; I <3; I ++) {Task. factory. startNew (letPersonSay);} Console. readKey ();} private static void letPersonSay () {Person emperor = Person. getInstance (); emperor. say () ;}} copy the code note: the following code displayed in the singleton Mode show is only required for testing and should be removed in formal use cases. Int I = 50000000; while (I> 0) {I --;} Singleton Mode show 1. Preliminary judgment of the hunger style singleton: delay Initialization is not supported, thread safety. Copy the code private Person () {Console. writeLine ("I initialized");} private static String name = "Jarvin"; private static Person instance = new Person (); public static Person getInstance () {int I = 50000000; while (I> 0) {I --;} return instance;} public void Say () {Console. writeLine ("I am {0}", name);} public static String getName () {return name;} copy the code for verification: analysis result: initialization is performed before the static method is executed (Jarvin string). Delayed Initialization is not supported. Then, the multi-thread mode is enabled. Verification passed. 2. Preliminary judgment of the lazy singleton: delay Initialization is supported, and threads are not secure. Copy the code private Person () {Console. writeLine ("I initialized");} private static String name = "Jarvin"; private static Person instance; public static Person getInstance () {if (instance = null) {int I = 50000000; while (I> 0) {I --;} instance = new Person ();} return instance;} public void Say () {Console. writeLine ("I am {0}", name);} public static String getName () {return name;} copy the code for verification: analysis result: before calling static methods Initialization, so delayed Initialization is supported. After multithreading, two initialization occurs. two Person-class instances are created, and the thread is insecure. Verification passed. 3. preliminary judgment of the internal class singleton: supports delayed initialization, and copies the code private Person () {Console. writeLine ("I initialized");} public static Person getInstance () {return SingleHelper. getEmperor ();} private class SingleHelper {private static Person emperor = new Person (); public static Person GetEmperor () {int I = 50000000; while (I> 0) {I --;} return emperor;} private static string name = "Jarvin"; public void Say () {Console. writeLin E ("I am {0}", name);} public static String getName () {return name;} copy the code for verification: analysis result: initialization is not performed before static methods are called, so delayed Initialization is supported. After multithreading is enabled, the initialization is performed only once, and the thread is secure. Verification passed. 4. preliminary judgment of the dual-check singleton: supports delayed initialization, and copies the code private Person () {Console. writeLine ("I initialized");} public static object Flag = new object (); public static Person me; public static Person getInstance () {if (me = null) {lock (Flag) {if (me = null) {int I = 50000000; while (I> 0) {I --;} me = new Person ();}}} return me;} private static string name = "Jarvin"; public void Say () {Console. writeLine ("I am {0}", n Ame);} public static String getName () {return name;} copy the code for verification. analysis result: initialization is not performed before the static method is called. Therefore, delayed Initialization is supported. After multithreading is enabled, the initialization is performed only once, and the thread is secure. Verification passed.

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.