23 design patterns (1) Java singleton pattern

23 design patterns Part 4: Java singleton pattern

definition:

Singleton pattern is a common software design pattern. Its core structure contains only a special class called singleton. The singleton pattern ensures that there is only one instance of a class in the system. That is, a class has only one object instance.

characteristic:

1. A singleton class can only have one instance. 2. A singleton class must create its own unique instance. 3. The singleton class must provide this instance to all other objects

Key points of singleton mode:

1. Private construction method 2. Private static reference to own instance 3. Static public method with own instance as return value

The singleton mode can be divided into two types according to the timing of instantiating objects:

One is the hungry man type single case, the other is the lazy man type single case. Hungry Chinese singleton instantiates an object and gives it a reference when the singleton class is loaded; The lazy type instantiates the object only when calling the get instance method.

The code is as follows:

Hungry Han style single case

Lazy single case

There is another common form of singleton mode: the form of double lock

In this mode, the synchronization content is transferred to the if, which improves the execution efficiency. It is not necessary to synchronize every time the object is obtained. It is synchronized only for the first time, and it is not necessary after it is created.

The double judgment plus synchronization mode in this mode is much more efficient than that in the first example, because if a single-layer if judgment is made, if the server allows, it is assumed that there are 100 threads, The time consumed is 100 * (synchronous judgment time + if judgment time). If double if judgment, 100 threads can judge if at the same time. The theoretical time consumed is only one if judgment time.

Therefore, in the case of high concurrency and lazy mode, the best choice is double judgment and synchronization.

Advantages of singleton mode:

1. There is only one object in memory to save memory space. 2. Avoiding frequent creation and destruction of objects can improve performance. 3. Avoid multiple occupation of shared resources. 4. Can be accessed globally.

Advantages of singleton mode:

1. The extension is difficult because the getInstance static function has no way to generate instances of subclasses. If you want to expand, you have to rewrite that class. 2. Implicit use causes unclear class structure. 3. Problems that cause program memory leaks.

Applicable scenarios:

Because of the above advantages of singleton mode, it is a design mode used more in programming. The following are scenarios using singleton mode: 1. Objects that need to be instantiated frequently and then destroyed. 2. Objects that take too much time or resources to create, but are often used. 3. In the case of resource sharing, avoid performance or loss caused by resource operation. 4. In the case of controlling resources, facilitate mutual communication between resources.

Precautions for singleton mode:

You can only use the methods provided by the singleton class to get the singleton object. Do not use reflection, otherwise a new object will be instantiated. Do not do the dangerous operation of disconnecting singleton class objects from static references in classes. Pay attention to thread safety when using shared resources by multithreading singleton.

Some common questions about singleton pattern in Java:

Will singleton mode objects be collected by the JVM garbage collector if they are not used for a long time

The JVM garbage collector will not recycle singleton objects unless the singleton static reference is disconnected from the singleton object artificially. The criteria for the JVM unloading class are as follows: 1. All instances of the class have been recycled, that is, there are no instances of the class in the Java heap. 2. The classloader that loads this class has been recycled. 3. The corresponding Java Lang. class objects are not referenced anywhere, and methods of this class cannot be accessed anywhere through reflection. Only when all three conditions are met will the JVM unload the class during garbage collection. Obviously, the singleton class does not meet condition 1, so the singleton class will not be recycled.

Will there be multiple singletons in a JVM

In the case of distributed systems, multiple class loaders, and serialization, there is no doubt that multiple singletons will be generated. Will singletons be generated in the same JVM? Using the getInstance () method provided by the singleton can only get the same singleton. Unless the reflection method is used, a new singleton will be obtained.

The code is as follows:

In this way, each run will produce a new singleton object. Therefore, when using singleton mode, be careful not to use reflection to generate new singleton objects.

Is there an advantage of synchronization on the getInstance () method, or is it better to synchronize only the necessary blocks?

Because locking only makes sense when an instance is created, and then other times the instance is only read-only, it is better to synchronize only the necessary blocks and is a better choice. Disadvantages: only in the first call can two objects be generated, and synchronization must be required. Once the singleton is not null, the system still costs synchronization lock overhead, which is a little more than worth the loss.

Can singleton classes be inherited

According to the timing and mode of single instance construction, single instance mode can also be divided into several types. However, inheritance is not supported for singleton classes that provide instances through privatized constructors and static methods. The singleton implementation of this pattern requires each specific singleton class to maintain singleton instances and limit the generation of multiple instances. However, another idea of realizing singleton can be adopted: registered singleton to make singleton open to inheritance.

Transferred from: Java confidant

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>