C # design pattern V2 (1) - Singleton

From: https://www.cnblogs.com/zhili/p/SingletonPatterm.html

 

I. Introduction

Recently some of the elements of design patterns, the main reference book is "Head First Design Patterns", while in the learning process but also see a lot of blog garden articles on design patterns, in here to record some of my study notes, First, in order to help me a better understanding of design patterns, and second, at the same time can give a friend some of the novice some reference design patterns. First, I introduce the design patterns in a relatively simple pattern - singleton (because there is only involves a class)

Introduction Second, the singleton

Speaking singleton, we should first reaction is - what is the singleton? From the "singleton" literally understood as - only one instance of a class, so the Singleton pattern is to ensure that only one instance of a class A Method Bale (design patterns in fact, help us solve the actual development process method, which is to reduce the degree of coupling between objects, but there are many solutions, so our predecessors to summarize some common solutions for the books, so this book is called design patterns) are given below the official definition of a singleton pattern: to ensure that only one instance of a class, and provide a global access point. To help better understand the singleton, we can bind to class diagram below appreciated and will be analyzed later to realize the idea of a single embodiment mode:

Third, why is there a singleton

After reading singleton introduction, naturally we will have such a question - Why should the Singleton pattern? It is used in what circumstances? Singleton pattern definition we can see - NATURAL single mode embodiment our system is that when an object requires only one example of the case where, for example: only one operating system task manager, file operation when, in the same time allowing only one instance of its operation, since there is such a real-life scenarios, naturally there must be such a solution in the field of software design (abstract because the software design is in real life), so it there will be a singleton pattern.

Fourth, the analysis of the realization of ideas Singleton

After understanding over some of the basic concepts of singletons, following the realization of ideas for everyone to analyze single-case model, because in my own learning singletons, a quick look at code that implements the Singleton pattern is indeed very simple, it is easy to understand, but I still think it is very strange (this may be watching less, or write your own code is also used less reason), but my heart will always such a question - Why is it so go predecessors singleton pattern to achieve it? How did they think of it? After pondering behind his ideas will slowly clear rationale to achieve a singleton pattern, and this time is no longer think Singleton unfamiliar, here to share my analysis of a process of:

Conceptually we singletons ( to ensure that only one instance of a class, and it provides access to a global access point) to start, the concept can be split into two parts: (1) ensure that only one instance of a class; (2) provide a global access point to access it; the following to help you quickly master the analysis of ideas through the use of two of the dialogue:

Rookie: how to ensure that only one instance of a class?

Much: Then let me help you down analysis, you create instances of the class will think of ways to create what is it?

Novice: with the new keyword ah, as long as the next creates a new instance of the class, and then you can use some of the attributes of the class and instance methods

Veterans: you ever wondered why you can use the new keyword to create an instance of the class do?

Rookie: The conditions there do? ......... oh, I think of it, if the class definition private constructor can not create new instances by the outside world (Note: Some beginners will ask, and sometimes I was not in class Why define a constructor can also be used to create new objects, it is because the compiler behind tampered with, and when we see that the compiler does not define the class constructor, then the compiler will help us generate a public no arg constructor)

Veterans: Yes, answer it right, so that your doubts will be answered, ah

Rookie: I want to create an instance of the class Where?

Veterans: you silly ah, of course, is to create a class inside (Note: this is a definition of private constructors thought process above to create an instance, naturally there should be a variable to hold the instance to, so there declare private variables, but implementation is the definition of static variable private, friends have not thought about - Why here defined as static it for this question of interpretation is: each thread has its own thread stack, defined as static? mainly to ensure that the class has a multi-threaded example )

Rookie: Oh, now completely understand, but I have another question - now the class instance creation within the class, how to get an instance of the outside world that to use it?

Veterans: Well, you can define a public method or property to put out a public instance of the class (Note: This will have the definition of a public method, the method is to provide global access point to ask class method)

Through the above analysis, we believe it is easy to write code that implements the singleton pattern, the following will look at the specific implementation code (After reading it you will be surprised: this is true!):

Copy the code
  /// <summary> 
    implement singletons /// 
    /// </ Summary> 
    public class the Singleton 
    { 
        // definition of a static class instance variable to hold the 
        Private the Singleton static uniqueInstance; 

        // private constructor is defined, so that the outside such instances can not be created 
        Private the Singleton () 
        { 
        } 

        /// <Summary> 
        /// method to provide a global definition of a public access point, and you can define a global public property to provide access point 
        /// </ Summary> 
        // / <returns> </ returns> 
        public static the GetInstance the Singleton () 
        { 
            // If the instance of the class does not exist it is created, otherwise it returns directly 
            IF (uniqueInstance == null) 
            { 
                uniqueInstance the Singleton new new = ();
            }
            return uniqueInstance;
        }
    }
Copy the code

 Example single-mode in the above single-threaded indeed perfect, however, in the case where a plurality of multithreaded Singleton will be instances, as when the two threads running simultaneously GetInstance method, and the two threads is determined (uniqueInstance = = null) return this condition is true, and the two threads will create an instance of Singleton, so contrary to our original intention of the singleton pattern, multiple threads of execution since the implementation above runs, then we are for multi-threaded GetInstance natural solution is to make the method at the same time run only one thread is running just fine , that is a question we thread synchronization (for thread synchronization you can refer to my thread synchronization of the article), the specific code to solve multi-threaded follows :

Copy the code
/// <summary> 
    implement singletons /// 
    /// </ Summary> 
    public class the Singleton 
    { 
        // definition of a variable to hold the static class instance 
        private static uniqueInstance the Singleton; 

        // definition of a synchronization identification thread- 
        private Readonly = Object Locker new new static Object (); 

        // private constructor defined in the class instance can not be created outside 
        private the Singleton () 
        { 
        } 

        /// <Summary> 
        /// method to provide a global definition of a public access point, and you public properties can also be defined to provide global access point 
        /// </ Summary> 
        /// <Returns> </ Returns> 
        public static the GetInstance the Singleton () 
        {  
            // when a first thread running here, at this time will locker object "lock"
            // when the second thread running the method, the first detected locker the object is "locked" state, the thread will hang waiting for the first thread to unlock 
            // After running (that is, after the thread runs out) lock Statement the object will "unlock" 
            Lock (Locker) 
            { 
                // If the instance of the class does not exist it is created, otherwise it returns directly 
                IF (uniqueInstance == null) 
                { 
                    uniqueInstance the Singleton new new = (); 
                } 
            } 

            return uniqueInstance; 
        } 
    }
Copy the code

Above this solution can really solve the problem of multi-threading, but the above code for each thread instance if there is a thread locker lock helper object after another judge, there is no need for this operation, as a thread is created when the first after an instance of the class, this time behind the thread just need to direct judgment (uniqueInstance == null) is false, then absolutely no need to go after the object locking thread auxiliary judge, so the above implementation adds additional expenses, loss of performance, in order to improve implementation of the above defects, we only need to add a (uniqueInstance == null) judgment can be avoided lock the increased overhead in front of the lock statement, this implementation we call it " double lock " , to achieve specific look at the following code:

Copy the code
  /// <summary> 
    implement singletons /// 
    /// </ Summary> 
    public class the Singleton 
    { 
        // definition of a variable to hold the static class instance 
        private static uniqueInstance the Singleton; 

        // definition of a synchronization identification thread- 
        private Readonly = Object Locker new new static Object (); 

        // private constructor defined in the class instance can not be created outside 
        private the Singleton () 
        { 
        } 

        /// <Summary> 
        /// method to provide a global definition of a public access point, and you public properties can also be defined to provide global access point 
        /// </ Summary> 
        /// <Returns> </ Returns> 
        public static the GetInstance the Singleton () 
        { 
            // when a first thread running here, at this time will locker object "lock"
            // When the second thread running the method, the object is first detected locker "locked" state, the thread will hang waiting for the first thread to unlock 
            // After running (that is, after the thread runs out) lock Statement the object will be "unlocked" 
            // double lock just a judgment on it 
            if (uniqueInstance == null) 
            { 
                lock (Locker) 
                { 
                    // instance is created if the class does not exist, or direct return 
                    if (uniqueInstance == null) 
                    { 
                        uniqueInstance the Singleton new new = (); 
                    } 
                } 
            } 
            return uniqueInstance; 
        } 
    }
Copy the code

Five, C # class is implemented in a single embodiment mode

 After understanding over singleton, the rookie went on to ask: .NET FrameWork library has not implemented a singleton it?

After See, .NET class library does exist to achieve single-mode embodiment, but the class is not disclosed, a look at the following specific implementation class (class System.dll specifically present in the assembly, namespace System, you can use the reflection tools reflector to view the source code):

Copy the code
// class is not a disclosed class 
    // implementation of this class, but use the single-mode embodiment 
    Internal Sealed the SR class 
    { 
        Private static the SR Loader; 
        Internal the SR () 
        { 
        } 
        // public mainly because the class is not, so that full access to the point is also defined as a private 
        @ mind is still used in the idea of singletons 
        private static GetLoader the SR () 
        { 
            IF (Loader == null) 
            { 
                the SR new new the SR = SR (); 
                Interlocked.CompareExchange <the SR> ( Loader REF, SR, null); 
            } 
            return Loader; 
        } 

        // this method calls the public GetLoader method 
        public static Object the GetObject (String name) 
        {
            SR loader = GetLoader();
            if (loader == null)
            {
                return null;
            }
            return loader.resources.GetObject(name, Culture);
        }
    }
Copy the code

VI Summary

After here, Singleton design pattern on introduction is over, we hope that through this article we can have a deeper understanding of the Singleton pattern, and want no contact before Singleton Singleton pattern or feel strange friends will be watching exclaimed: I see!

Guess you like

Origin www.cnblogs.com/frank0812/p/11302105.html