Design Mode-from shortest to deep Singleton mode, design mode example Mode

Source: Internet
Author: User

Design Mode-from shortest to deep Singleton mode, design mode example Mode

Speaking of the singleton mode, we may all be familiar with it. It can be said that it is the most frequently used in the design mode. to thoroughly list examples, I will explain here what is Singleton, the evolution of the singleton mode is different from that of static classes.

1: Concept

What is a singleton? In an application, only one instance is allowed, that is, the object can only be new once.

2: lazy Mode

Lazy, I think this name is very good, and it is very lazy. So when other objects are loaded, it will not be loaded. When you call me, I will load it. Similar to hibernate, there is also a lazy mode. OK. Let's get started.

2.1: Non-thread security

One day, James went to the interview. The interviewer said, you wrote a singleton Model for me. I thought it was too easy to think about. Soon I wrote the following Singleton model.

 1 public class Singleton { 2     private static Singleton singleton; 3     public static Singleton getSingleton() 4     { 5         if(singleton==null) 6         { 7             singleton=new Singleton(); 8         } 9         return singleton;10     }11 }

Then the interviewer said: You may have multiple singleton instances during high concurrency. How can I solve this problem? The interviewer explained that if there are two threads T1, run T2 at the same time. When T1 is executed to 6th rows, the time segment is reached. The system starts to execute T2, runs to 9th rows, and then T1 starts to execute again, because T1 has already been judged and does not know that singleton has been instantiated, singleton is instantiated again at this time, so that your system has two singleton objects. Is that a singleton object? James suddenly realized that, I can solve this problem, and I will immediately write the following:

2.2: thread security
 1 public class Singleton { 2     private static Singleton singleton; 3      4     public synchronized static Singleton getSingleton() 5     { 6         if(singleton==null) 7             { 8                 singleton=new Singleton(); 9             }10             return singleton;11     }

The interviewer saw that with thread synchronization, thread security issues could be guaranteed at this time, but he raised another question. If singleton has been instantiated now, and if 10 threads are simultaneously accessed, every time you wait, it will inevitably cause a huge performance consumption. Do you have any other solutions to solve the problem? James thought for a minute and wrote the following code

2.3: Dual Verification
 1 public class Singleton { 2     private static Singleton singleton; 3      4     public  static Singleton getSingleton() 5     { 6         if(singleton==null) 7         { 8             synchronized (Singleton.class) { 9                 if(singleton==null)10                 {11                     singleton=new Singleton();12                 }13             }14         }15         return singleton;16     }

At the interviewer's glance, the above Code has actually improved a lot of performance and reduced unnecessary waiting time. However, after a closer look, you may have a problem with this code, the thread security cannot be guaranteed. What does James say? Then, the interviewer explained: if there are T1 and T2 threads, the sixth line of T1 thread runs and singleton = null, the first step is to instantiate singleton, because the instantiation is divided into three steps. The first step is to open up the memory space for the object, and the second step is to initialize the object, the third step is to assign this memory address to singleton, but because the java memory mode allows unordered write, this will lead to the second and third steps of the location change, then this will break down, if Step 1 and Step 3 are allowed, but the object is not initialized at this time, T2. at this time, T2. after judging that singleton is not null, then an uninitialized object is returned. James heard that he was right. He said that I should change the memory mode to not allow unordered writing. So I changed the code

1 public class Singleton {2 privateVolatileStatic Singleton singleton; // indicates sequential write 3 4 public static Singleton getSingleton () 5 {6 if (singleton = null) 7 {8 synchronized (Singleton. class) {9 if (singleton = null) 10 {11 singleton = new Singleton (); 12} 13} 14} 15 return singleton; 16}

Note 1: three steps to Object Instantiation I will make a metaphor here. A company assigns a dormitory to its employees (that is, it opens up space in the heap) then, let's give the House a standard analogy of dividing the air conditioner, washing machine or something (object initialization), and then give the key to the employee (Object assignment ).

3: Hungry Chinese

The interviewer asked you how to write the "Hungry Man" model. James heard: Oh, hungry man, Don't you just want to instantiate it immediately, for fear that you can't instantiate it? This simple article immediately writes a hungry man

public class Singleton {        private static Singleton singleton=new Singleton();    public  static Singleton getSingleton()    {        return singleton;    }}

The interviewer looks really good.

4: Internal Class Mode

Let's look at the above model. I had a whim. In the hungry Chinese mode, I was anxious to create objects and consume performance during loading. In the lazy mode, there was a thread security problem (no more after optimization) can you combine them? I suddenly told the interviewer that I had a better way to implement it. Then he wrote the following code:

1 public class Singleton {    2     static class SingletonManager{3         private final static  Singleton SINGLETON=new Singleton();4         public final static Singleton getSingleton()5         {6             return SingletonManager.SINGLETON;7         }8     }

At the interviewer's glance, it was good, ensuring both lazy loading and thread security.

5. Use Cases

The interviewer asked James again, do you know the Application Scenario? James thought about it. Since there is only one Singleton in the application, it is bound to be used to share resources, which is similar to the database connection pool, thread pools can all be used in singleton mode.

6: differences between singleton mode and static class

The interviewer continued to ask: static classes also generate an object, which is highly similar to singleton. Do you know their differences? James replied

1: objects are subject to three major features: inheritance, encapsulation, and polymorphism, but static classes cannot be inherited. Therefore, static classes do not conform to the object orientation from the oo perspective, their classes cannot be covered, so they are more flexible than a single instance.

2: due to the special nature of the static class, it has been instantiated in the compiler and cannot provide the lazy loading mode.

3: For unit tests in projects, it is also difficult to test because the methods cannot be covered.

4: Since static classes have been instantiated in the compiler, the performance is faster than that of a single instance. If you only need to execute some static methods, you can use static classes.

7. Summary

The Singleton mode seems simple. In fact, many problems need to be taken into account. Now I have summarized this process. Of course, there may be some shortcomings. please correct me.

 

Related Article

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.