Author: Qian Jue

Email address: [email protected]

Official account: Qian Jue (Jue)

Title: Singleton Patterns of Design Patterns

Hello, gentlemen, I am back to update you. If you follow my trends, you should know that I sent a flag saying that I would complete the design mode during the Chinese New Year holiday. As a result, it has already been three months and I still haven’t finished it.

This few days I have been thinking about how to write these design patterns, because there are too many online about the wheels of the design patterns, we have been advocating is with wheels, don’t repeat the creation of a wheel, the design of the online mode tutorial is much, but thousands of Jue think of those who write online is a bit too much trouble, so they think of themselves in creating the wheel again.

Good not nonsense, begin to enter the body below, what this period thousand jue speaks is the singlecase pattern in the design pattern, also be thousand jue thinks comparatively easy to understand the design pattern.

What is the singleton pattern

Convention first on baidu encyclopedia above the introduction.

The singleton pattern is a common software design pattern belonging to the creation type. Classes created by singleton methods have only one instance in the current process (depending on the need, it is also possible to use the same instance in a thread context).

Qian Jue’s understanding of the singleton pattern is that classes created through the singleton pattern can have only one instance at a time in an application

When do we use the singleton pattern, for example, if you have a configuration file class in your application, you can only have one instance at a time in the entire application, if you have multiple instances, if you want to change the configuration class, it’s very easy to get an exception. (Don’t ask qian – chueh why she knew. She would cry bitterly.)

Let’s look at a few ways to make singletons.

Lazy mode

public class Singleton {

   // Create a static instance

    private static Singleton singleton;

   // Restrict arbitrary creation of singleton patterns

    private Singleton(a){}

    // Give a public static method that returns a singleton

    public static Singleton getInstance(a){

      // Create an instance only if the instance is empty

        if(singleton == null) {

            singleton = new Singleton();

        }

        return singleton;

    }

}

Copy the code

This is the standard singleton pattern without regard to concurrency. Once you put a program with concurrent requests, the program will have multiple instances, which is not the singleton pattern.

Let me give you a concurrent example to test it out, in case some of you ask qian Jue why she is not singleton in concurrent requests, if you are lying to us. Qian – chueh is a good man and can’t lie [Dog head]

Why to concurrent will create multiple instances, because when concurrent access to a thread has not been created before the instance when another thread is in the instance is not yet created, judging it again, this time because a thread before you don’t create good, so this thread also creates an instance of This is why there are multiple instances in this singleton pattern.

To solve this situation, we thought that the simplest would be the following form.

public class SynchroizedSingleton {

    private static SynchroizedSingleton singleton;

    private SynchroizedSingleton(a){}

    public synchronized static SynchroizedSingleton getInstance(a){

        if(singleton == null) {

            singleton = new SynchroizedSingleton();

        }

        return singleton;

    }

}

Copy the code

The above code works in concurrent applications, but it’s too slow, and while one thread accesses this method, all the other threads are in a waiting state.

We can optimize the above class as long as the singleton instance is not created, after the instance is created, the method to get the instance does not need to be synchronized, so we can optimize the above code to look like this.

public class SynchroizedSingleton {

    private volatile static SynchroizedSingleton singleton;

    private SynchroizedSingleton(a){}

    public static SynchroizedSingleton getInstance(a){

        if(singleton == null) {

            synchronized(SynchroizedSingleton.class){

              if(singleton == null) {

                singleton = new SynchroizedSingleton();

              }

            }

        }

        return singleton;

    }

}

Copy the code

The code above is a lot of books on a standard double locking, why also determine the tune in the synchronized block instance is empty, because if a thread is created instance ready to return to, another thread came in at this time, if no judgment in the synchronized block that can create multiple instances, Why volatile? Because you should write the instance to main memory as soon as you create it, if you don’t write it, the judgment in the synchronized block is useless.

If you don’t know what volatile means, drop me a comment, and I’ll write an article about volatile if there’s a crowd. Keep an eye on me.

The hungry mode

Hangry singleton

public class Singleton {

    private static Singleton singleton = new Singleton();

    private Singleton(a){}

    public static Singleton getInstance(a){

        return singleton;

    }

}

Copy the code

The code above is the simplest singleton pattern, but Qian jue does not recommend using this method. The disadvantage of this method is that if I use the static method of this class but I do not intend to use this instance, I will waste memory.

Another way is to use inner classes

public class Singleton {

    private Singleton(a){}

    public static Singleton getInstance(a){

        return SingletonInstance.singleton;

    }

    private static class SingletonInstance{

        static Singleton singleton = new Singleton();

    }

}

Copy the code

The singleton is still a singleton because static variables are initialized only once.

conclusion

Above is singlecase pattern basic writing method, if have omission still ask everybody big guy to be added below, thousand jue is here first thanked. The introduction of the singlecase mode to write may have some problems, trouble leaders do not spray Thousand jue, after all, thousand jue or Java learning road novice. Thank you for watching. The next phase will introduce the factory mode in design mode. If you are interested, please click “like” and “follow”. You are also welcome to find me in wechat and search qianjue (Jue) on wechat.

Insert a picture description here