First, this program is marked
- What is a singleton mode
- Single-Instance pattern class diagram
- Singleton Pattern Code
- Application of single-case model
Ps:java design Mode Series course, this is the last section of the class. I believe that we learn all the way down or harvest quite abundant, now think back to the learning of those design patterns, I believe you will soon have a similar to such a Lenovo fragment:
- Factory mode: Nu wa empress ...
- Abstract Factory Model: kitchen, food, foodie ...
- Adapter mode: Port version iphone6, charging head, adaptor ...
- Decorator mode: A lot of different kinds of girlfriends ...
- Viewer mode: Video website, American drama ...
Did you find it? Through this kind of memory, the knowledge points are connected together, you will remember more solid and clearer, this is what we do well-intentioned place. (Not modest ...) So I hope everyone to study well, day up!
Although the story is very tired, but in order to benefit the majority of children's shoes, the story has to continue. Let ' s go!
Second, what is a singleton mode
The singleton pattern (Singleton pattern), as the name implies, is that only one instance of an object in the case can exist. A singleton pattern is implemented by a class that returns a reference to an object (always the same) and a method that obtains that unique instance (which must be a static method). Through the singleton mode, we can guarantee that there is only one instance in the system, so as to save or control the system resources in certain situations.
Three, single case pattern class diagram
In "Decorator Mode", we experience the "acid cool" of a girlfriend with a variety of different characteristics ... But the dream is plump, the reality is very skinny, finally you can only have a wife. (Ah hello, Sao years, in fact, girlfriend can only have one!) What the? You said you had a lot of ex-girlfriends. You think I didn't say ... )
Iv. sample code for a singleton pattern
Talk is cheap, show me the code.
Before you learn this lesson, you may have heard or learned about the "singleton pattern". But do you know how many ways the singleton pattern is implemented? This looks the simplest design pattern, actually has many pits ...
1. A Hungry man mode
One of the most common and simplest examples of single-mode patterns. As the name implies, "A Hungry man mode" is very "hungry", so you need to give it a new instance. But there is one obvious drawback to this approach, which is to getWife() create a new instance each time, regardless of the method that has been called to obtain the instance (in this case).
// 饿汉模式public class Wife { // 一开始就新建一个实例 private static final Wife wife = new Wife(); // 默认构造方法 private Wife() {} // 获得实例的方法 public static Wife getWife() { return wife; }}
2. Lazy mode
The most common and simplest model of the singleton two, with "A Hungry man mode" is "good base friends." Again, as the name implies, "lazy mode" is that it is very lazy, at first do not create a new instance, only when it needs to use, it will first determine whether the instance is empty, if it is empty to create a new instance to use.
// 懒汉模式public class Wife { //一开始没有新建实例 private static Wife wife; private Wife() { } // 需要时再新建 public static Wife getWife() { if (wife == null) { wife = new Wife(); } return wife; }}
3. Thread-Safe Lazy mode
Does it feel simple? But there is a serious problem with the lazy model above. That is, if more than one thread calls getWife() the method in parallel, it creates multiple instances, and the singleton mode fails.
Bug come, change change!
Simply, let's set it to Thread Sync () in the basic lazy mode synchronized . is to ensure that there is synchronized at most one thread running at the same time, thus avoiding problems with multithreading. For synchronized keywords, you can click here to learn more.
//lazy mode (thread safe) public class wife { Private static Wife Wife; private Wife () {} //added synchronized keyword public static synchronized Wife getwife () {if (wife = = null) {wife = new Wife ();} return wife;}
4. Double Inspection Lock (double check)
The thread-Safe lazy mode solves the problem of multithreading and looks perfect. However, it is not efficient, each call to obtain the method of the instance getWife() to synchronize, but in most cases do not need synchronization operations (for example, my wife instance is not empty can be used directly, there is no need to getWife() add synchronous method, directly return to the wife instance). Therefore, you only need to use the synchronization method when you first create a new instance object.
Not afraid, the program ape always have a way. So, on the basis of the previous, there is a "double Test lock" method.
//dual-lock Getwife () method public static Wife getWife () {//the first inspection lock, if not NULL directly returns the instance object, is empty before entering the next if (wife = = null) {synchronized (wife.class) {//the second inspection lock because there may be multiple threads entering the IF statement within the Span class= "Hljs-keyword" >if (wife = = null) {wife = new Wife ();} }} return wife;}
You think this is finally complete? NO ... Too Young, Too naive! The main problem is wife = new Wife() this code, because when the JVM (Java virtual machine) executes this code, to do a few things, and the JVM in order to optimize the code, it is possible to do these things the order of execution is not fixed, resulting in errors. (in order not to complicate the problem, there is no in-depth explanation of what is going on in the JVM, and interested students can click here to learn about it.) )
At this point, we need to add a volatile keyword to the instance, which is to prevent the compiler from optimizing the code itself. Finally, our "double check lock" version was finally released ...
Double Test lockpublic class wife {private volatile static Wife Wife; private Wife () {} public static Wife getwife () { if (wife = null) {synchronized ( Wife.class) {if (Wife = null) {Wife = new Wife ();}}} return wife;}
5. Static Inner class
The above method, tinkering, is really too complicated ... and volatile the keyword does not work in some older versions of the JDK. We have to change the method, that is, "static inner class". In this way, the JVM's own mechanism is used to ensure thread safety because WifeHolder the class is private and getWife() there is no other way to access the instance object than getWife() to actually create the instance object at the time of the call. (This is similar to "lazy mode")
//static inner class public class wife {private static class Wifeholder {private static final Wife Wife = new Wife (); private Wife () {} public static Wife getwife () { return wifeholder.wife;}
6. Enumeration
Still do not understand what is enumerated, first make up the missed lesson.
As you can see, the code is simply not easy anymore. We can Wife.INSTANCE access the instance object through it, which getWife() is much simpler than it is, and creating an enumeration by default is thread-safe and can also prevent problems with deserialization. The NIU (BI) approach comes from the new version of the effective Java book. This method is not commonly used, but is most recommended.
// 枚举public enum Wife { INSTANCE; // 自定义的其他任意方法 public void whateverMethod() { }}
Application of single-case model
When you only need an instance object, you can consider using singleton mode. For example, in the case of resource sharing, avoid the performance or loss caused by multiple resource operations, you can use the singleton mode.
Vi. reference Documentation
- Java Design Pattern:singleton
Singleton mode of design mode