6. Singleton pattern (Singleton Pattern) Mentioned earlier that the five create a model, the main problem is how to create objects, access to products. The Singleton pattern is most to be concerned about the number of objects created and when to be created.

Singleton pattern can be very simple, it's all just a class can be completed (see the UML diagram in this chapter the poor). But if "the object was created and when the number of times to create" two points up on the Jiao Zhen, Singleton pattern can be quite complex, than the first five modes together make up complex, for example, double-lock detection related to DCL (double checked locking) discussion, involving multiple class loader (ClassLoader) coordination when it comes to cross-JVM (clusters, remote EJB, etc.), involved a single case of reconstruction after the object is destroyed. For complex cases, this chapter will be involved in some of the [1]

Objective:

Hope to create an instance of an object only, and provide a global access point.

Scene:

Kerrigan for the Zerg is essential for the heart and soul of countless Drone, Zergling, Hydralisk ... ... can be created, to be sacrificed, but to a Zerg Kerrigan relationship may exist in the Bureau of the game's survival, but Kerrigan is not allowed to be repeatedly created, there must be one and only one instance of the Zerg Queen of Blades exist, it is not rules of the game, but this is a political issue.

Analysis:

As mentioned earlier, we still try to use the access code to describe the process of Kerrigan, see the following UML diagram, so simple that I do not account for how nerve to not impress layout.

Figure 6.1 UML diagram Singleton Pattern

Structure is simple, but we have some small requirements are as follows:

1. The most basic requirements: Every time from getInstance () can return one and only one Kerrigan object. 2. Slightly higher requirements: Kerrigan busy, many people find, so I hope this method can adapt to multi-threaded concurrent access. 3. And then raise the requirements a bit: Zerg is to pay attention to the civil service efficient society, hoping to find a way Kerrigan performance as high as possible. 4. The final requirement is that Kerrigan themselves: the understanding that Kerrigan tired, want more time to sleep, so Kerrigan hope to achieve lazy loading (Lazy Load), the macro will only need to construct. 5. Originally intended to deal with that also feed more ClassLoader, multi-JVM, etc., but still not to be considered a too complex for the time being let off on the first bar (-_-#).

We write the single case of the first model is the following look like this:

Java code to copy the code

/ ** * To achieve a single case of a first attempt to access Kerrigan * / public class SingletonKerriganA (

The wording of the demand we have four points from top to bottom inspection and found the second time on a problem, assuming that such a scenario: Two concurrent threads calling SingletonKerriganA.getInstance (), assuming thread is complete instance of a first determines whether the null both in the code line A to line B to enter the location. After just judge, JVM CPU resources will switch to thread 2, thread one yet because the implementation of line B, so instance is still empty, so the second thread executed new SignletonKerriganA () operation. Shortly after, the thread was re-awakened one, it is still the implementation of new SignletonKerriganA () operation, well, question is, who is two Kerrigan Li Kui Li Gui who is?

Then, we do a single case of Mode's second try:

Java code to copy the code

/ ** * To achieve a single case of Kerrigan's second attempt to visit * / public class SingletonKerriganB (

Than the first piece of code more than just a synchronized method modifier can now be guaranteed not to the thread question. But there are big (at least time-consuming a large proportion of) performance problems. In addition to the first call is executed SingletonKerriganB constructor, the next call to each object instance is returned directly. Back to object this time-consuming operation is very small, most of the time-consuming and are synchronized with the synchronized modifier to prepare, so from a performance that is not worth.

It continues to change the code like the following:

Java code to copy the code

/ ** * To achieve a single case of Kerrigan's third attempt to visit * / public class SingletonKerriganC (

Basically, the code inside the synchronized move is meaningless, and every call to getInstance () still have to be synchronized. Synchronization itself is no problem, but we only hope that in the first instance to create Kerrigan to synchronize the time, so we have the following wording - double check locking (DCL).

Java code to copy the code

/ ** * To achieve a single case of the fourth attempt to access Kerrigan * / public class SingletonKerriganD (

We look this way requirements have been met, except for the first time to create the object, the other in the first visit if in the back, it will not come synchronized block. Is perfect yet?

We take a look at this scenario: Suppose one execution thread to the instance = new SingletonKerriganD () phrase, here appears to be a word, but in fact it is not an atomic operation (atomic operations, which means that this statement or to be executed finished, or not being performed, can not appear in half the implementation of such cases). High-level language which in fact there are many non-atomic operation Let us look at this sentence Pi compiled Houzai JVM assembly code implementation Duiying discovered that these words are compiled into eight assembly instruction, Tai Zhizuo the three things:

1. To allocate memory for an instance of Kerrigan. 2. Initialized constructor Kerrigan 3. The instance object points to the allocated memory space (note this step instance a non-null).

However, the Java compiler allows the processor to-order execution (out-of-order), and JDK1.5 before the JMM (Java Memory Medel) in the Cache, registers to main memory write-back provisions of the order, and the second point above The third point of order is not guaranteed, that is, the implementation of the order may also be 1-3-2 1-2-3, if the latter, and is finished in 3 and 2 before execution, be switched to thread 2, this time instance as it has been implemented within the thread after a third point, instance has a non-empty, so the thread took two direct instance, and then use, then logical error, and this is difficult to track difficult to reproduce the error estimates may not be able to debug on the find a week out of the cup is really a coffee table with ah.

DCL is drafted to achieve a single case of many technical books, textbooks (including those based on JDK1.4 previous versions of books) on the written recommendation, it is not entirely correct. Indeed, in some languages (such as C language) on the DCL is feasible, depending on whether the order of steps to ensure 2,3. In JDK1.5, the government has taken note of this issue, so adjust the JMM, the concrete of the volatile keyword, so if JDK 1.5 or later, just to change the instance of the definition of "private volatile static SingletonKerriganD instance = null; "you can guarantee that each instance is from the main memory to read, you can use DCL to complete the drafting of a single case of mode. Of course, will affect the performance of more or less volatile, the most important thing is we have to consider JDK1.42 and earlier versions, so in this article written a single case of model improvement continues.

Code pour more and more complex, and now the first to a back to nature, according to JLS (Java Language Specification) the provisions, a class in a ClassLoader will be initialized in one, this is guaranteed JVM itself, then the JVM instance initialization throw things right, the code was changed to this:

Java code to copy the code

/ ** * To achieve a single case of the fifth attempt to access Kerrigan * / public class SingletonKerriganE (

Well, if this is the perfect wording, then the previous several paragraphs, then it is on fun of you readers. The wording does not appear complicated problem, but it is a hungry man-style, in the ClassLoader class loads an instance of post-Kerrigan will be created the first time, a hungry man is created style will not be available in a number of scenarios: for example Kerrigan creation is dependent on the parameters of an instance or configuration files, in getInstance () must be called before a method to set parameters to it, as a single case of this formulation can not be used.

Let's look at the following address more that I think can a single case of written scenarios:

Java code to copy the code

/ ** * To achieve a single case of the sixth attempt to access Kerrigan * / public class SingletonKerriganF (

The wording still use their own mechanism to ensure the JVM thread-safety issues; as SingletonHolder is private, in addition to getInstance () than there is no way to access it, so it is a lazy style; the same time will not be read when an instance of synchronization, no performance deficiencies; not rely on JDK version.

Other single cases of model formulation there are many, such as the use of local threads (ThreadLocal) to deal with concurrency and to ensure that a thread within a single case of implementation, GoF use the original case, a single case of class registration form Yingdui need to inherit when the need to achieve, using the designated to deal with multi-class loader ClassLoader environment to achieve more. Development of the design work we do, it shall have to consider the possible expansion of demand and changes, we should also avoid "phantom demand" caused unnecessary to upgrade the design, implementation complexity, which would ultimately bring about the duration, the loss of performance and stability . Over-design and design are less than harm, so that there is no single case of the best mode, only the most appropriate mode of single cases.

Up to this single case of model itself on the first end, and finally introducing the structure from a single case of other means of shielding the object method:

1. Direct new singleton object 2. Singleton object through reflection structure 3. Constructed by a single case of object serialization.

In the first case, the general we will add a private or protected constructor, so the system will not automatically add the public constructor, so can only be called inside the static method can not create new objects.

For the second case, reflection method can be used to break through the private setAccessible constraints, we need to do the first work, also need the ReflectPermission ("suppressAccessChecks") permission to use the security manager (SecurityManager)'s checkPermission method to limit this break. In general, do not really do these things are the background through the application server configuration to achieve.

For the third case, if the single case of objects necessary to achieve Serializable interface (rare), you should also realize readResolve () method to ensure that, when deserializing get the original object.

Based on the above, the single case of mode two additional methods:

Java code to copy the code

/ ** * To deal with most situations to achieve a single case of * / public class SingletonKerrigan implements Serializable (

This chapter again and again attempt to understand the mode of a single case of the advantages and disadvantages of various implementations. Detection of the double lock lock a brief discussion, I believe that everyone in the evolution of various attempts to understand why the Singleton pattern is the simplest and most complex model of a structure.

Between the various structural models can be compared with each other, but not the merits good or bad, only identified the context, can we talk about what kind of mode. Learning Design Patterns I have no need to think back some code templates Jiang, Should to understand each model De Chu Xian's Yuan Yin and resolve, when you find your design requirements Gengda flexibility O'clock, design would be the model toward Geshi evolution, this time you really grasp the design mode.

Related Posts of Explore the design patterns of 6 - Singleton Pattern

Financial crisis has come, the project got worse, employees are brothers, should not because there is no project, on vacation or dismissal. However, small businesses, how many did not make money, can only help each other to tide over the difficulties. As

What is a Design Pattern Design patterns are a set of re-use, most people know, after cataloging, code design experience. For the use of design patterns are reusable code, so that the code more easily understood by others, and ensure the reliability code.

Software development process at the design and coding, both organizations (as well as other details of the project controllability requirements) engineering method is XP ah, UPS ah what the design phase is to cover the entire software development pro ...

I hate the thought of the time to teach some provide a lot of code, because I think the thought process of acceptance should be a pleasure to read as a novel process, rather than spend a lot of brain power for a certain process details And this world ...

Master the ability to reuse code very familiar with the new API's fast. This is because, he once used a lot of the API, have a lot of reusable code. He knows what is available and what is deficient. He has been using Qt, also used by gtk +, also used

Technical article ] [IT168 As an IT technical staff, that no one person is willing to Forever in the bottom of the preparation procedure or to do simple maintenance. After a period of technology and the accumulation of experience, a lot of people are ...

Project Leader: assessment needs to change some of the workload to determine whether it needs to change the contents of the progress on the development of an impact, if the demand to change the progress of an impact on the development, the project le ...