A simple model of the singleton design pattern

 
To put it simply, the singleton pattern

       means that in an application, there is only one instance object of a certain class, and you cannot go to new, because the constructors are modified by private, and their instances are generally obtained through the getInstance() method. The return value of getInstance() is a reference to an object, not a new instance, so don't mistake it for multiple objects.

    The singleton pattern is also very easy to implement, but a lot of use of the singleton pattern may cause memory leaks, because once the singleton object is created, it will be saved in the heap, and the garbage collector cannot clear the reference to this object, because the hot spot itself is The "reference chain reachability method" is used to determine whether to recycle, and the single existence of a singleton will cause a strong reference and cannot be cleared. In this way, the objects accumulate, and out of memory will occur!

    There are generally three ways to implement the singleton pattern: lazy singleton, hungry singleton, and registered singleton.

Write the code directly below: lazy thread-safe singleton

     

// Lazy thread safe singleton 
public  class Singleton {

    private static Singleton singleton;

    private Singleton() {
    }

    public static Synchronized Singleton getInstance() {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }
}   


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325170203&siteId=291194637