Http://www.yesky.com/softchannel/72342380484755456/20040731/1837286.shtml
[Article] Author: Mark Townsend Time: 2004-08-02 Source: MSDN June issue of development Featured Editor: Ark
[Document] In this article, we will discuss the Singleton mode, which is included in the creative mode series.
[text]
During the development of the software application, repeatability is repeated as the application is developed. With the development of the entire software system, many of the same models will gradually appear. This repetitive mode concept is very obvious in other applications. Car manufacturing is a kind of such application. Many different automotive models use the same sub-components, including most basic components (eg, bulbs and fastening parts) and larger components (eg, chassis and engines). In residential buildings, repetitive mode concepts apply to screws and screws and overall overall building power distribution systems. Regardless of the formation group is to develop new car design or new building design, it usually does not have to take into account the previously resolved issues. If the group of design and building residential buildings must rethink and design each component of the house, the time spent on the whole process is much longer than now. Many design decisions such as door or light switch feature (for example, door height or light switch feature) are easy to understand. In order to meet the requirements of the handle function to meet the houses, the house designer does not have to redesign and re-build different types of water supply and water storage facilities to meet the requirements for the handles of the handles of the house: standard sink and standard heat Water and cold water input joints and drain output joints are very easy to understand the very common house building components. The repetitive mode concept can be repeatedly applied to almost everything around us, including software. Examples of cars and residential buildings contribute to some general abstract concepts in software design and construction. Easy to understand and clearly defined the concept of universal functional components is the source of design patterns, and it is also the focus of other two design patterns in studying plant design models and exploration of observer design patterns. These modes cover almost all aspects of object-oriented software design, including object creation, object interactions, and object survival. In this article, we will discuss the Singleton mode, which is included in the creative mode series. Creative mode indicates how and when to create an object. Many instances need only special behaviors that can be solved by creative methods, rather than enforcing the required behavior after creating instances. One of the best examples of such behavior requirements is included in the Singleton mode. Singleton Mode In "Design mode: can be used for object-oriented software", there is formal definition in the classic reference book, including Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides (also known as four people Group or GOF). In design mode, this mode is the simplest and one of the most widely used modes. However, as we will see, some problems may occur when implementing this mode. This article tries to analyze the Singleton mode from the header through multiple early implementations of Singleton mode, and how to play its best use in Microsoft .NET application development. Singleton Mode is based on the definition in the design mode is the use of Singleton mode. . What problems can be solved, or in other words, what is our motivation? Almost in each application, there is a need to have a region where globally accessed and maintains a type of data. There is also this situation in an object-oriented (OO) system, in which a set of predefined number of predefined numbers of a class or a class should only be run at any given time. For example, when using a class to maintain an increment counter, this simple counter class needs to track integer values used in multiple applications. Such a need to increase the counter and return the current value. For this case, the desired class behavior should only use one class instance to maintain the integer, not to use other class instances to maintain the integer.
Initially, people may try to create a counter class instance as a static global variable. This is a common method, but in fact solves some problems; it solves global accessibility issues, but does not take any measures to ensure only one class instance is run at any given time. It should be taken by the class itself to use only one class instance, not by a class user. You should always let the user to monitor and control the number of class instances running. What you need is to use some way to control how to create class instances, then make sure you only create a class instance at any given time. This will provide us with the required behavior and make the client do not have to know any kind of details. The logical model Singleton model is very simple and intuitive. (Usually) only one Singleton instance. The client accesses the Singleton instance through a known access point. In this case, the client is an object that needs to access the unique Singleton instance. Figure 1 shows this relationship in a graphical manner.
Physical model Singleton mode physical model is also very simple. However, over time, it is slightly different in the way Singleton. Let's take a look at the original gofsingleton implementation. Figure 2 shows the UML model of the original Singleton mode defined by the design mode.
We see a simple class chart that displays private static properties with a Singleton object and a public method instance () that returns this same property. This is actually the core of Singleton. There are other properties and methods for explaining other operations that are allowed on this class. In order to facilitate this discussion, let us focus on instance properties and methods. The client only accesses any Singleton instances through an instance method. There is no way to create an instance here. We also want to control how and when to create an instance. In OO development, you can usually process the creation behavior of special objects in the constructor of the class. This situation is no exception. What we can do is defining when we and how to construct a class instance, and then disable any client directly call the constructor. This is a method that is always used in the Singleton configuration. Let's take a look at the original example in the design mode. Typically, the C Singleton example implementation of the C Singleton shown below is considered as the default implementation of Singleton. This example has been ported to many other programming languages, usually it is almost the same in any place. C Singleton example implements code
// Declarationclass Singleton {public: static Singleton * Instance (); protected: Singleton (); private: static Singleton * _instance;} // Implementation Singleton * Singleton :: _ instance = 0; Singleton * Singleton :: Instance () {if (_Instance == 0) {_instance = new singleton;} return _instance;} Let's take some time to analyze this code. This simple class has a member variable, which is a pointer to this class. Note that the constructor is protected and only public methods are example methods. In an instance method implementation, there is a control block (IF) that checks if the member variable has been initialized. If not, create a new instance. This inert initialization in the control block means initialization or creation of a Singleton instance only when the instance () method is called for the first time. This method is very good for many applications. But for multi-threaded applications, this approach demonstrates that there is a potentially dangerous side effect. If the two threads enter the control block simultaneously, two instances of the member variable may be created. To solve this problem, you may want to put the important part only around the control block to ensure thread security. If you do this, you will serve all the calls of the instance method and may have adverse effects on performance (depending on the application). It is because of this reason, another version of this mode is created, which uses a certain functionality called a double inspection mechanism. The next code example shows a double inspection lock using the Java syntax. Use Java syntax double-checked locking Singleton Code // C port to Javaclass Singleton {public staticSingletonInstance () {if (_instance == null) {synchronized (Class.forName ( "Singleton")) {if (_instance == null) { _INSTANCE = New Singleton ();}}} Return_Instance;} protected} private statunicleton_instance = null;} In the Singleton code example, we directly transplanted C code directly to Java code in order to use the Java syntax Use the Java key block (synchronized). The main difference is no longer a separate statement and implementation, without a pointer data type, and has adopted a new dual inspection mechanism. Dual test occurs on the first IF block. If the member variable is empty, perform the entry key section, which is double-tightened again. The member variable is only instantiated after this final test. In general, two threads cannot create two class instances using this method. In addition, because there is no thread blocking in the first check, most calls to this method do not result in performance due to the need to enter the lock. Currently, this method is widely used in many Java applications when implementing Singleton mode. This method is very clever, but there is also a flaw. Some optimized compilers can optimize the inert initialization code or re-sort them and re-generate thread security issues.
The logical model Singleton model is very simple and intuitive. (Usually) only one Singleton instance. The client accesses the Singleton instance through a known access point. In this case, the client is an object that needs to access the unique Singleton instance. Figure 1 shows this relationship in a graphical manner. Physical model Singleton mode physical model is also very simple. However, over time, it is slightly different in the way Singleton. Let's take a look at the original gofsingleton implementation. Figure 2 shows the UML model of the original Singleton mode defined by the design mode.
We see a simple class chart that displays private static properties with a Singleton object and a public method instance () that returns this same property. This is actually the core of Singleton. There are other properties and methods for explaining other operations that are allowed on this class. In order to facilitate this discussion, let us focus on instance properties and methods. The client only accesses any Singleton instances through an instance method. There is no way to create an instance here. We also want to control how and when to create an instance. In OO development, you can usually process the creation behavior of special objects in the constructor of the class. This situation is no exception. What we can do is defining when we and how to construct a class instance, and then disable any client directly call the constructor. This is a method that is always used in the Singleton configuration. Let's take a look at the original example in the design mode. Typically, the C Singleton example implementation of the C Singleton shown below is considered as the default implementation of Singleton. This example has been ported to many other programming languages, usually it is almost the same in any place. C Singleton example implements code
// Declarationclass Singleton {public: static Singleton * Instance (); protected: Singleton (); private: static Singleton * _instance;} // Implementation Singleton * Singleton :: _ instance = 0; Singleton * Singleton :: Instance () {if (_Instance == 0) {_instance = new singleton;} return _instance;} Let's take some time to analyze this code. This simple class has a member variable, which is a pointer to this class. Note that the constructor is protected and only public methods are example methods. In an instance method implementation, there is a control block (IF) that checks if the member variable has been initialized. If not, create a new instance. This inert initialization in the control block means initialization or creation of a Singleton instance only when the instance () method is called for the first time. This method is very good for many applications. But for multi-threaded applications, this approach demonstrates that there is a potentially dangerous side effect. If the two threads enter the control block simultaneously, two instances of the member variable may be created. To solve this problem, you may want to put the important part only around the control block to ensure thread security. If you do this, you will serve all the calls of the instance method and may have adverse effects on performance (depending on the application). It is because of this reason, another version of this mode is created, which uses a certain functionality called a double inspection mechanism. The next code example shows a double inspection lock using the Java syntax. Double inspection locking Singleton code using Java syntax