C # Design Patterns study notes: (1) singleton

    This excerpt from the note: https://www.cnblogs.com/PatrickLiu/p/8250985.html , learning about the recording for subsequent lookup.

    I. Introduction

    Design pattern Category:

    1) in accordance with the purpose of:

    Create a model (Creational) mode: responsible for object creation

    Structural (Structural) mode: the processing composition between the object and class

    Behavioral (Behavioral) mode: the allocation of responsibilities in the class and object interaction

    2) in accordance with the scope of:

    Class modes: static relationship processing classes and subclasses

    Object modes: dynamic relationship between the processing target

    Note: This series of articles according to the purpose of classification.

    Introduction Second, the singleton

    Singleton: English Name Pattern --Singleton; Classification - Create Type; definitions - only one instance of a class.

    2.1, motivation (Motivate)

    In software systems, often have such special classes, they must ensure that there is only one instance in the system, in order to ensure their logical correctness, and good efficiency.

    How to bypass the conventional construction, providing a mechanism to ensure that only one instance of a class? It should be the responsibility of the designer category, but not the responsibility of the user.

    2.2, intent (Intent)

    Ensure that only one instance of a class, and provide a global point of this example. - "Design Patterns GoF"

    2.3, the structure of FIG. (Structure)

    2.4, the composition mode

    There is only one mode of this type, the type is Singleton, and only one instance of this class, the method may obtain an instance of the type by Instance ().

    2.5, code implementation

    Since it is a single instance, it will certainly involve multi-threading problems.

    2.5.1 Singleton achieve single-threaded mode

    class Program 
    { 
        ///  <Summary> 
        /// single-mode embodiment
         ///  </ Summary> 
        public  Sealed  class the Singleton 
        { 
            // definition of a static class instance variable to hold the 
            Private  static the Singleton uniqueInstance; 

            // defined private constructor function, so that the outside world can not create an instance of the class. 
            Private the Singleton () 
            { 
                Console.WriteLine ( " the Singleton object has been created. " ); 
            } 

            ///  <Summary> 
            /// defined method provides a global public access points, public property may also be defined to provide global access point.
            ///  </ Summary> 
            /// <Returns> </ Returns> 
            public  static the Singleton the GetInstance () 
            { 
                // If the instance of the class does not exist is created, otherwise it returns directly. 
                IF (uniqueInstance == null ) 
                { 
                    uniqueInstance = new new the Singleton (); 
                } 
                return uniqueInstance; 
            } 
        } 

        static  void the Main ( String [] args) 
        { 
            #region (. 1) singletons
             var Singleton = Singleton.getInstance (); 
            Console. the Read (); 
            #endregion
        }
    }
View Code

    Results are as follows:

    Private instance constructor is shielded outside calls to achieve Singleton pattern above in a single thread is really perfect, also good to meet the needs of our single-threaded environment.

    In a multithreaded environment, use the Singleton pattern is still possible to get multiple instances of an object class Singleton. Because when you run two threads simultaneously GetInstance method,

At this time, two threads are returned true judgment (uniqueInstance == null) this condition, when two threads will create an instance of the Singleton.

    2.5.2 Multithreading to achieve Singleton pattern

    class Program 
    { 
        ///  <Summary> 
        /// single-mode embodiment
         ///  </ Summary> 
        public  Sealed  class the Singleton 
        { 
            // definition of a static class instance variable to hold the 
            Private  static  volatile the Singleton uniqueInstance; 

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

            // define a private constructor, so that the outside world can not create an instance of the class. 
            Private Singleton () 
            { 
                Console.WriteLine ( " Singleton object has been created. " );
            } 

            ///  <Summary> 
            /// defined method provides a global public access point may define a global public property to provide access point.
            ///  </ Summary> 
            ///  <Returns> </ Returns> 
            public  static the Singleton the GetInstance () 
            { 
                // when a first thread running here, this case 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 the lock statement End run (ie after the thread runs out) the object will "unlock." 
                Lock (Locker) 
                { 
                    // If there is no instance of a class is created, otherwise direct return 
                    IF (uniqueInstance == null ) 
                    { 
                        uniqueInstance= new Singleton();
                    }
                }
                return uniqueInstance;
            }
        }

        static void Main(string[] args)
        {
            #region (1)单例模式
            for (int i = 1; i <= 10; i++)
            {
                Thread thread = new Thread(new ParameterizedThreadStart(Worker));
                thread.Start(i);
            }
            Console.Read();
            #endregion
        }

        private static void Worker(object parameter)
        {
            Console.WriteLine($"Thread {parameter} is running.");
            Singleton.GetInstance();
        }
    }
View Code

    Results are as follows:

    The above solutions can indeed solve multi-threading problems, but the above code each thread after thread locker lock helper object instance and then determine whether there is, this is completely unnecessary.

Because when the first thread creates an instance of the class, this time behind the thread just need to direct judgment (uniqueInstance == null) can be false, thereby reducing the additional costs to improve performance.

    In order to improve the above defects implementations, we only need to add a determination (uniqueInstance == null) in front of the lock statement, this double lock if added implementation, we call

"Dual Lock (Double Check)".

    class Program 
    { 
        ///  <Summary> 
        /// single-mode embodiment
         ///  </ Summary> 
        public  Sealed  class the Singleton 
        { 
            // definition of a static class instance variable to hold the 
            Private  static  volatile the Singleton uniqueInstance; 

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

            // define a private constructor, so that the outside world can not create an instance of the class. 
            Private Singleton () 
            { 
                Console.WriteLine ( " Singleton object has been created. " );
            } 

            ///  <Summary> 
            /// defined method provides a global public access point may define a global public property to provide access point.
            ///  </ Summary> 
            ///  <Returns> </ Returns> 
            public  static the Singleton the GetInstance () 
            { 
                // when a first thread running here, this case 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 the lock statement End run (ie after the thread runs out) the object will "unlock"
                . // double lock just a judgment on it 
                IF (uniqueInstance == null ) 
                { 
                    Lock (Locker) 
                    { 
                        // create if there is no instance of a class, or direct return
                        if (uniqueInstance == null)
                        {
                            uniqueInstance = new Singleton();
                        }
                    }
                }
                return uniqueInstance;
            }
        }

        static void Main(string[] args)
        {
            #region (1)单例模式
            for (int i = 1; i <= 10; i++)
            {
                Thread thread = new Thread(new ParameterizedThreadStart(Worker));
                thread.Start(i);
            }
            Console.Read();
            #endregion
        }

        private static void Worker(object parameter)
        {
            Console.WriteLine($"Thread {parameter} is running.");
            Singleton.GetInstance();
        }
    }
View Code

    volatile modifications : In order to fine-tune the compiler to compile the code, when will the code, with the volatile modified to ensure the strict sense of order. A definition for volatile variable is that this variable may

Is unexpectedly changed, so the compiler would not have to assume that the value of this variable. Precisely that, every time the optimizer must be carefully re-read the value of this variable when use this variable,

Instead of using a backup stored in registers.

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

    Now we look at how to use the characteristics of the C # language to achieve Singleton pattern singleton.

        // achieve Singleton pattern 
        public  Sealed  class Singleton 
        { 
            public  static  Readonly Singleton instance = new new Singleton (); 

            Private Singleton () {} 
        } 

        // upper inline initialized (initialized simultaneously generated) single-mode embodiment, which is equivalent to: 

        public  Sealed  class the Singleton 
        { 
            public  static  Readonly the Singleton instance; 

            // static constructor, CLR performed only once. 
            static the Singleton () 
            { 
                instance = new new the Singleton (); 
            } 

            //Private constructor against external call 
            Private the Singleton () {} 
        }

    Inline initialization is actually the static field into a static constructor to initialize. As long as you want to access a static field, will have to perform a static constructor prior to use, this can ensure the use of accurate

When you will be able to get instance, if you do not use will not instantiate the object, which is loaded delay function. It also supports multi-threaded environment, because there can be only one thread to perform static structure

, Multiple threads does not exist to perform static constructor (the feeling is that the program has been automatically locked us up).

    It is a little drawbacks: the static constructor can only be declared as a private, no-argument constructor, so examples of the method parameter is not supported.

    Incidentally: HttpContext.Current is a single embodiment, it is extended by way of Singleton achieved.

    Extended four, Singleton mode

    1) an instance extended to n instances, for example, to achieve the target pool. (N does not refer to an infinite number of examples, but a fixed number.)

    2) the call is transferred to a new configuration of other classes, such as classes plurality of collaborative work environment, the need to have only a local environment an instance of a class.

    3) and the core appreciated Singleton pattern is extended, "the user how to control any calls to a new instance of the class constructor."

    Achieve five points, Singleton pattern

    1) Singleton pattern is to limit rather than improve the class is created.

    2) Singleton class instance Protected constructor may be provided to allow the subclassing.

    3) Singleton pattern generally do not support Icloneable interfaces, as this may result in multiple object instances, contrary to the original intention of the Singleton pattern.

    4) Singleton pattern generally do not support serialization, which could also lead to more object instances, which is contrary to the original intention of the Singleton pattern.

    5) Singleton consider only managed objects that are created, management does not consider destroyed. Why do it? Because Net platform is to support garbage collection, so we generally do not need to be destroyed

deal with.

    6) and a core appreciated Singleton pattern is extended, "the user how to control any new call to the constructor of a class."

    7) can easily modify a Singleton, it has a few examples, this is permissible and meaningful.

    Singleton pattern advantage 5.1

    1) Examples of control: Singleton will prevent other objects instantiate a copy of its own Singleton object to ensure that all objects have access to a unique instance.

    2) Flexibility: Because the class instantiation process control, it can be more flexible to modify class instantiation process.

    Singleton pattern disadvantage 5.2

    1) cost: Though rare, but should be checked every time you requested object references are instances of the class exist, will still require some overhead, can initiate to resolve this issue by using static.

    2) may confuse developers: use the Singleton object (especially the objects defined in the class library), the developer must remember that they can not use the new keyword to instantiate an object. Because there may be no

French access library source code, so application developers may find themselves unexpectedly can not be directly instantiated.

    Lifetime 3) objects: Singleton does not solve the problem delete a single object. Because it contains a reference to a static private fields, static fields can not be recovered CLR memory of the real

And as long as regular application life cycle, there has been.

    5.3 singleton usage scenarios

    1) When only one instance of the class and the customer can access it from a well-known access point.

    2) When this single example should be extended by subclassing, and the customer should be able to use the code without changing an extended example.

Guess you like

Origin www.cnblogs.com/atomy/p/12145865.html