Talking about lazy loading from the lazy singleton pattern

First talk about what is the [singleton pattern]

First of all, the singleton pattern is one of the object creation patterns, in addition to the factory pattern. Three characteristics of the singleton pattern:
1. The class has only one instance
2. The class creates the instance by itself (creates its own instance object within the class)
3. Exposes the instance interface to the entire system

  1. Hungry-style singleton mode

The characteristic is: a new object is created at the beginning of the definition

public class Singleton
{   
    private static final Singleton s = new Singleton();
    private Singleton(){}
    public static Singleton getInstance(){
        return s;
    }
}

  1. Lazy singleton pattern

The characteristic is: the new object is only when the new object is really needed.

public class Singleton
{   
    private static Singleton s = null;
    private Singleton(){}
    public static Singleton getInstance(){
        if(s != null){
            synchronized(Singleton.class){
                if(s != null)
                    s = new Singleton();
            }
        }
    }
}

According to the above two codes, the second code adopts [lazy loading] , that is to say: lazy loading is to instantiate the object when it really needs to be instantiated.

Leave a Comment

Your email address will not be published. Required fields are marked *