C # design mode (1) -- Singleton Mode

Source: Internet
Author: User
I. Introduction

Recently, some of the content in the design pattern is mainly referenced in the book head first design pattern. At the same time, I also checked some of the design patterns in many blogs.ArticleHere, 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.CompositionOnly one instance is allowed to perform operations at a time. Since such an application scenario exists 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, let's take a look at the implementation of Singleton mode.CodeIt is really simple and easy to understand, but I still think it is very unfamiliar (this may be because of a small amount of reading or writing code ), there is always a 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 Singleton Mode  ///   </Summary>      Public   Class  Singleton {  //  Define a static variable to save the instance of the class          Private  Static  Singleton uniqueinstance;  //  Defines private constructor so that you cannot create such instances.          Private  Singleton (){}  ///   <Summary>          ///  Define a public method to provide a global access point. You can also define a public attribute to provide a global access point.  ///   </Summary>          ///   <Returns> </returns>          Public  Static  Singleton getinstance (){  //  If the instance of the class does not exist, it is created; otherwise, it is returned directly.              If (Uniqueinstance = Null  ) {Uniqueinstance = New  Singleton ();}  Return  Uniqueinstance ;}} 

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 Singleton Mode  ///   </Summary>      Public   Class  Singleton {  //  Define a static variable to save the instance of the class         Private   Static  Singleton uniqueinstance;  //  Define an identifier to ensure Thread Synchronization          Private   Static   Readonly   Object Locker = New   Object  ();  //  Defines private constructor so that you cannot create such instances.          Private Singleton (){}  ///   <Summary>          ///  Define a public method to provide a global access point. You can also define a public attribute to provide a global access point.  ///   </Summary>          ///   <Returns> </returns>          Public   Static  Singleton getinstance (){  //  When the first thread runs here, it will lock the locker object ", //  When the second thread runs this method, the locker object is first detected as "locked", and the thread will wait for the first thread to unlock.  //  After the lock statement is run (that is, after the thread is run), the object is "Unlocked"              Lock  (Locker ){  //  If the instance of the class does not exist, it is created; otherwise, it is returned directly.                  If (Uniqueinstance = Null  ) {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 Singleton Mode  ///   </Summary>      Public   Class Singleton {  //  Define a static variable to save the instance of the class          Private   Static  Singleton uniqueinstance;  //  Define an identifier to ensure Thread Synchronization          Private   Static   Readonly   Object Locker = New   Object  ();  // Defines private constructor so that you cannot create such instances.          Private  Singleton (){}  ///   <Summary>          ///  Define a public method to provide a global access point. You can also define a public attribute to provide a global access point.  ///   </Summary>          ///   <Returns> </returns>          Public   Static  Singleton getinstance (){ //  When the first thread runs here, it will lock the locker object ",  //  When the second thread runs this method, the locker object is first detected as "locked", and the thread will wait for the first thread to unlock.  //  After the lock statement is run (that is, after the thread is run), the object is "Unlocked"  //  You only need to judge the double lock.              If (Uniqueinstance = Null  ){  Lock  (Locker ){ //  If the instance of the class does not exist, it is created; otherwise, it is returned directly.                      If (Uniqueinstance = Null  ) {Uniqueinstance = New  Singleton ();}}}  Return  Uniqueinstance ;}} 
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 checking, the. NET class library does have an implementation class of the singleton mode, but this class is not public. Let's take a look at a specific implementation of this class (this class exists in system. dllProgramSet, the namespace is system, you can use the reflection tool reflector to view the source code ):

 //  This class is not a public class  //  However, 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.  // However, the idea is still based on the singleton model.          Private   Static  Sr getloader (){  If (Loader = Null  ) {SR = New  Sr (); interlocked. compareexchange <Sr> ( Ref Loader, Sr, Null  );}  Return Loader ;}  //  This public method calls the getloader Method          Public   Static   Object GetObject ( String  Name) {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!

 

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.