Design Patterns - Singleton Pattern

Hungry Chinese:

class Ehan{
    private Ehan(){}
    private static Ehan singleton = new Ehan();
    public static Ehan getInstance(){
        return singleton;
    }
}

Regarding the hungry singleton pattern, there is no risk of multiple instances being created. Because the class has only one instantiation operation, which is to initialize the object when the class is loaded.

 

Lazy Man:

  Double check:

  

class Baohan{
    private Baohan(){}
    private volatile static Baohan singleton;
    public static Baohan getInstance(){
        if(singleton == null){
            synchronized (Baohan.class){
                if(singleton == null){
                    singleton = new Baohan();
                }
            }
        }
        return singleton;
    }
}

Regarding the lazy singleton pattern, the object will be instantiated only when it is called, which belongs to lazy loading. And in order to ensure that the problem of multiple objects does not occur in a multi-threaded environment, synchronized locking is used in the method, and the variable is modified with the volatile keyword, thereby avoiding the problem of incomplete instantiation caused by instruction reordering. Another way is to use inner static classes.

Reference link: https://blog.csdn.net/justloveyou_/article/details/64127789

 

Guess you like

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