C # design mode (1) -- Singleton mode,

Source: Internet
Author: User

C # design mode (1) -- Singleton mode,
Original article address: http://www.cnblogs.com/zhili/p/singletonpatterm.html#introduction

Recently, some of the content in the design pattern is mainly referenced in the book Head First design pattern. In the course of study, I also read some articles about the design pattern in many blog parks, here I will record some of my study notes. One is to help me better understand the design patterns, and the other is to give some reference to some new design patterns. First, I will introduce a simple mode in the design mode-singleton mode (because only one class is involved here)

II. Introduction to singleton Mode

When talking about the singleton mode, the first response should be-what is the singleton mode ?, A singleton literally means that a class has only one instance, so the singleton mode isEnsure that a class has only one implementation method for one instance (the design pattern is actually to help us solve the method in the actual development process, this method is to reduce the coupling between objects, however, there are many solutions, so our predecessors have summarized some common solutions as books, so this book is called the design model)The following is an official definition of the singleton mode:Make sure that a class has only one instance and provides a global access point.To help you better understand the singleton mode, you can use the following class diagrams to understand the singleton mode and analyze the implementation ideas of Singleton mode later:

Iii. Why is the singleton mode available?

After reading the introduction of the singleton mode, you will naturally have such a question-why is there a singleton mode? Under what circumstances does it use? From the definition of Singleton mode, we can see that the use of Singleton mode is a situation where only one instance is needed for an object in our system. For example: the operating system can only have one task manager. When operating a file, only one instance is allowed to operate on it at a time. Since there are such application scenarios in real life, naturally there must be such a solution in the field of software design (because software design is also an abstraction in real life), so there is a singleton model.

Iv. Exploring the implementation of Singleton Mode

After learning about some basic concepts about the singleton mode, I will analyze the Implementation ideas of the singleton mode for you, because when I learned the singleton mode myself, the implementation code of the singleton mode is very simple and easy to understand, but I still think it is very unfamiliar (this may be rare, or I use less code), and I always have this question in my mind-why did our predecessors implement the singleton mode like this? How do they think? After thinking about the implementation of the singleton mode, I will gradually understand the implementation of the Singleton mode, and I will not feel the singleton mode at this time. The following will share my analysis process:

From the concept of Singleton mode (Make sure that a class has only one instance and provides a global access point to it)First, you can split the concept into two parts: (1) ensure that a class has only one instance; (2) provide a global access point to access it; the following uses a two-person conversation to help you master the analysis ideas faster:

Cainiao: how to ensure that a class has only one instance?

Old bird: Let me help you to analyze how you can create a class instance?

Newbie: Use the new Keyword. If new is used, an instance of this class is created. Then, you can use some attributes and instance methods of this class.

Old bird: Have you ever wondered why you can use the new keyword to create a class instance?

Cainiao: Are there any conditions for this ?........., Oh, I think of it. If a class defines a private constructor, it will not be able to create instances through new outside. (Note: Some beginners will ask, sometimes I have not defined the constructor in the class. Why can I use new to create objects? That's because the compiler is behind the scenes. When the compiler sees that no constructor is defined in our class, in this case, the compiler will generate a public no-argument constructor)

Old bird: That's good. The answer is right, so that your questions will be answered.

Cainiao: Where can I create a class instance?

Old bird: You are stupid. Of course, you have created a private constructor in the class. (Note: To define a private constructor, you need to create an instance, there is a variable to save the instance, so there is a private variable declaration,But the implementation is to define static private variables. have you ever wondered-why is it static? This question is explained as follows: each thread has its own thread stack, which is defined as static mainly to ensure that the class has an instance in multiple threads.)

Cainiao: Well, I understand it all now, but I still have another question: How can I obtain an instance to use it when a class instance is created inside the class?

Old bird: You can define a public method or attribute to publish the instance of this class (Note: This defines the public method, this method is used to provide global access points for the method Query Class)

Through the above analysis, we believe that it is easy for everyone to write the implementation code of the singleton mode. Let's look at the specific implementation code (you will be surprised after reading it: this is really the case !) :

/// <Summary> /// implementation of the Singleton mode /// </summary> public class Singleton {// defines a static variable to save the private static Singleton uniqueInstance of the class; // define a private constructor so that you cannot create a private Singleton () {}/// <summary> // define a public method to provide a global access point, you can also define public attributes to provide global access points /// </summary> /// <returns> </returns> public static Singleton GetInstance () {// if the instance of the class does not exist, it is created. Otherwise, if (uniqueInstance = null) {uniqueInstance = new Singleton () ;}return uniqueInstance ;}} is returned ;}}

The implementation of the Singleton mode above is indeed perfect in a single thread, but multiple Singleton instances will be obtained in the case of multiple threads, because when the GetInstance method is run in both threads at the same time, at this time, when both threads determine (uniqueInstance = null) This condition returns true, then both threads will create Singleton instances, which violates the original intention of the Singleton mode, since the above implementation will run multiple threads for executionOur solution to multithreading is naturally to make the GetInstance method run only one thread at a time.That is, the thread synchronization problem (for thread synchronization, you can also refer to my thread synchronization Article). The specific code to solve multithreading is as follows:

/// <Summary> /// implementation of the Singleton mode /// </summary> public class Singleton {// defines a static variable to save the private static Singleton uniqueInstance of the class; // define an identifier to ensure that the thread synchronizes the private static readonly object locker = new object (); // defines the private constructor so that the outside world cannot create such instances private Singleton () {}/// <summary> /// defines a public method to provide a global access point, you can also define public attributes to provide global access points /// </summary> /// <returns> </returns> public static Singleton GetInstance () {// when the first thread runs here, the locker object will be locked. // when the second thread runs this method, first, it is detected that the locker object is in the "locking" status, and the thread will suspend waiting for the first thread to unlock. // After the lock statement is run (that is, after the thread is run) the object will be "Unlocked" lock (locker) {// if the instance of the class does not exist, it will be created; otherwise, if (uniqueInstance = null) will be returned directly) {uniqueInstance = new Singleton () ;}} return uniqueInstance ;}}

The above solution can solve the problem of multithreading,The above code locks the thread-assisted object locker in each thread and then checks whether the instance exists. This operation is completely unnecessary because after the first thread creates an instance of this class, at this time, the subsequent threads only need to directly judge (uniqueInstance = null) as false. At this time, there is no need to lock the auxiliary thread object before judging, therefore, the above implementation method adds additional overhead and reduces performance. To improve the defects of the above implementation method, we only need to add a sentence (uniqueInstance = null) before the lock statement) to avoid the additional overhead of the lock. This implementation method is called "double lock"To see the specific implementation code:

/// <Summary> /// implementation of the Singleton mode /// </summary> public class Singleton {// defines a static variable to save the private static Singleton uniqueInstance of the class; // define an identifier to ensure that the thread synchronizes the private static readonly object locker = new object (); // defines the private constructor so that the outside world cannot create such instances private Singleton () {}/// <summary> /// defines a public method to provide a global access point, you can also define public attributes to provide global access points /// </summary> /// <returns> </returns> public static Singleton GetInstance () {// when the first thread runs here, the locker object will be locked. // when the second thread runs this method, first, it is detected that the locker object is in the "locking" status, and the thread will suspend waiting for the first thread to unlock. // After the lock statement is run (that is, after the thread is run) the object will be "Unlocked" // double lock only requires one sentence to determine if (uniqueInstance = null) {lock (locker) {// if the instance of the class does not exist, it is created. Otherwise, if (uniqueInstance = null) {uniqueInstance = new Singleton () ;}} return uniqueInstance ;}} is returned ;}}
V. classes that implement the singleton mode in C #

After understanding the singleton mode, cainiao went on to ask: Is there any Singleton mode implementation in the. NET FrameWork class library?

After viewing ,. NET class library does exist in the singleton mode implementation class, but this class is not public. Let's take a look at a specific implementation of this class (this class exists in System. dll assembly, namespace is System, you can use the reflection tool Reflector to view the source code ):

// This class is not a public class // but the implementation of this class applies the singleton mode internal sealed class SR {private static SR loader; internal SR () {} // This is mainly because this class is not public, so all access points are also defined as private. // but the idea still uses the private static SR GetLoader () idea of the singleton mode () {if (loader = null) {SR sr = new SR (); Interlocked. compareExchange <SR> (ref loader, sr, null);} return loader;} // This public method calls the public static object GetObject (string name) of the GetLoader Method) {SR loader = GetLoader (); if (loader = null) {return null;} return loader. resources. getObject (name, Culture );}}
Vi. Summary

Here, we have finished introducing the singleton mode of the design mode. I hope you can have a deeper understanding of Singleton mode in this article, I also hope that my friends who have never been familiar with the singleton mode or who are unfamiliar with the singleton mode will be amazed at the fact that this is the case!

Related Article

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.