This is the 22nd day of my participation in the More text Challenge. For details, see more text Challenge


👉 Design mode directory

What is the singleton pattern
1. The concept

The singleton pattern is a common software design pattern belonging to the creation type. The class created by the method of singleton mode has only one instance in the current process (according to the need, there may also be a thread belonging to the singleton, such as: only thread context using the same instance)

The singleton pattern is to strictly control the instance of a class, requiring that only one instance exists in a process or a thread. If not, an instance is created and returned, and if there is, an already existing instance is returned. Different singleton patterns are used to ensure that there is only one instance.

2. Common examples

Like the official seal of a company, generally a company has only one, this official seal can be regarded as a single case, only really lost to replace.

The singleton pattern is used in the case of a system I wrote that needed to read configuration information from a database that was not intended to change after formal deployment. Each startup is read from the database and then encapsulated as a Map singleton, with each individual system using its own singleton. In fact, in development, need to manually add, modify the database configuration is very troublesome 😭

Characteristics of 3.
  1. Only one instance of a singleton class can exist in a process or thread.
  2. The constructor of a singleton class must be privatized. No other class is allowed to create a singleton class, only it can create itself.
  3. Singletons need to provide other classes with a way to get an instance, usually statically.
Advantages of 4.
  1. Reduced memory overhead. Because the singleton pattern is strictly limited to a single instance, this greatly reduces the memory overhead of repeatedly creating instances.
  2. Easier to manage and maintain. There’s nothing to say, it’s all in this class, you just need to change this class.
5. Shortcomings
  1. It’s not very scalable. The singleton pattern focuses on the fact that only one instance can exist, at the expense of extensibility.
  2. Conflict with single responsibility. Because all methods are encapsulated in singletons, they get bigger and their responsibilities become less and less clear.
The principle of 6.

“+” means compliance, and “-” means noncompliance or irrelevant

The principle of Open the closed Single responsibility Di milt Replacement on the Richter scale Dependency inversion Interface segregation Synthesis of reuse
+ +
Second, the classification of singleton pattern
1. The hungry
concept

Like a hungry man encounter food, all at once. A hungrier singleton, when you load the.class file, it generates an instance in the static area, and all other classes call that class.

code
package singletion;
/ * * *@authorXXJ * Hungry single case */
public class HungrySingletion {
    private static HungrySingletion instance=new HungrySingletion();
    private HungrySingletion(a){}
    public static HungrySingletion getInstance(a){
        returninstance; }}Copy the code
The characteristics of

It is simple to create an instance in the static area at the beginning. This ensures thread safety and will not produce redundant instances, but the created instances will lead to slow initialization. The next singleton pattern solves this problem.

2. LanHanShi
concept

A slob is lazy and will never do anything until he is on fire. Lazy singletons, which generate instances only when they call methods that provide instances to other classes, can have some threading problems.

Simple – lazy

code

package singletion;
/ * * *@authorXXJ * Lazy singleton */
public class LazySingleton {
    private static LazySingleton instance=null;
    private LazySingleton(a){}
    public static LazySingleton  getInstance(a){
    	if(instance==null)
        instance=new LazySingleton();
        returninstance; }}Copy the code

The characteristics of

At first instance points to null, so it doesn’t generate an instance in the static area at first, but it loads lazily, but it has threading problems. This is not a singleton pattern at the extreme of creating multiple instances once multiple threads have access to the instance fetching method at the same time, so the next lazy pattern solves this problem.

Double check – slacker

code

package singletion;
/ * * *@authorXXJ * Double check lazy singleton */
public class DoubleCheckLazySingleton {
    private static volatile DoubleCheckLazySingleton instance =null;

    public static DoubleCheckLazySingleton getInstance(a) {
        if (instance==null) {synchronized (DoubleCheckLazySingleton.class){
                if (instance==null){
                    instance=newDoubleCheckLazySingleton(); }}}return instance;
    }
    private DoubleCheckLazySingleton(a) {}}Copy the code

Double check

Simply put, the first check is for efficiency, since not all threads will be able to run through the loophole. This one check will intercept most threads. The second check solves the thread safety problem by adding the synchronized keyword, which solves the multithreading problem by locking it.

The characteristics of

It inherits the lazy loading characteristics of simply-lazy singletons and solves the thread safety problem. The only drawback is that the structure is complex.

There is also a slacker singleton pattern that has fewer second checks than the double-checked slacker singleton, which solves the thread-safety problem of a small number of threads, but cannot be guaranteed with more threads.

Here are two less common singleton patterns.

3. Static inner classes
code
public class Singleton {  
    private static class SingletonHolder {  
    	private static final Singleton instance = new Singleton();  
    }  
    private Singleton (a){}  
    public static final Singleton getInstance(a) {  
    returnSingletonHolder.instance ; }}Copy the code
explain

This singleton pattern using static inner class is actually an upgraded version of hunhun-style. First, a static inner class is created inside the singleton class, which contains an instance of the singleton class. Then, the singleton class provides another class with a method to get an instance. When another class calls this method, the class loader loads the inner class, and when it does, an instance of the singleton class is generated.

The characteristics of

It not only inherits the hunhun-style thread safety feature, but also implements the function of lazy loading.

4. The enumeration class
code
package singletion;
/ * * *@authorXXJ * Enumeration class singleton pattern */
public enum  EnumSingleton {
    INSTANCE;
    public static EnumSingleton getInstance(a) {
        returnEnumSingleton.INSTANCE; }}Copy the code
The characteristics of

First of all, even though the implementation is simple and convenient, implementing singletons with an enumeration class is actually the same as the hunhuns. It is thread-safe, but it is also slow to initialize. One more thing, enumeration classes do do singleton, I’ve verified hashCode, they’re all the same, but the way it’s written is a little confusing.

Third, summary

In general, use huns and enumerations, use simply-lathier for lazy loading, double check for thread safety, or just use static inner classes.

— — — — — — — — — — — — — — —

The more you know, the more you don’t know.

If you have questions about this article, please comment directly or send me a personal message. If you think my writing is good, you can also support me by clicking “like”

Without permission, shall not be reproduced!