Singleton: There must be at most one object of a class at a time! You may try to get the object many times, but you will get the same object!

Suppose you have a King class in your project:

public class King {}Copy the code

Obviously, it is not singleton at present, because it can:

King k1 = new King();
King k2 = new King();
King k3 = new King();
Copy the code

This code creates three objects of type King! If you want to implement a singleton, you must first restrict access to the constructor, for example:

public class King {
    private King(a) {}}Copy the code

Each class can have several constructors, and if a class does not explicitly declare any constructors, the compiler automatically adds a public, no-argument constructor! If any constructors are already declared in a class, the compiler does not automatically add constructors!

Since the constructor is declared private, the original King k1 = new King(); This kind of code cannot be used to create objects!

Restrict access to constructors. The purpose is to “disallow arbitrary object creation”, not “disallow object creation”. Inside the King class, objects can still be created, and methods can be added to return internally created objects:

public class King {
    private King king = new King();
    
    private King(a) {}public King getInstance(a) {
        returnking; }}Copy the code

So, when you need an object of type King, you can get it using the getInstance() method!

However, the above code is not feasible! Because if you want to call getInstance(), you must first get the King object, and the only way to get the King object is to call getInstance()! To solve this problem, the static modifier must be added before the declaration of the getInstance() method, and finally, through the class name. The syntactic format of the method name () to call the method! The global king attribute must also be static, because “static members cannot access other members that are not static” :

public class King {
    private static King king = new King();
    
    private King(a) {}public static King getInstance(a) {
        returnking; }}Copy the code

At this point, the basic singleton pattern code design is complete!

The above code is the hungrier singleton pattern, and there is also the lazy singleton pattern!

The code for the basic lazy singleton is:

public class King {
    private static King king = null;
    
    private King(a) {}public static King getInstance(a) {
        if (king == null) {
            king = new King();
        }
        returnking; }}Copy the code

Note: the above code is multithreaded unsafe!

In the development world, whenever data is produced or changed differently than the developer expected, it is called an “insecure” or “data security problem.”

To ensure thread-safety, the code snippet that created the object above should be “locked”, for example:

public class King {
    private static King king = null;
    
    private King(a) {}public static King getInstance(a) {
        synchronized ("hello") {
            if (king == null) {
                king = newKing(); }}returnking; }}Copy the code

Of course, whenever any thread executes the above code, it must “lock” the code snippet before it can start executing. This is not necessary, and the performance cost of “locking” is wasteful, so it can be further adjusted to:

public class King {
    private static King king = null;
    
    private King(a) {}public static King getInstance(a) {
        if (king == null) { // Determine if it is necessary to lock the following code
            synchronized ("java") {
                if (king == null) { // Determine if it is necessary to create an object
                    king = newKing(); }}}returnking; }}Copy the code

Now the lazy singleton pattern is complete!