Several ways to achieve singleton design pattern

1. starving mode, the static constant way

Hungry man model avoids the problem of thread synchronization, as it was when the class was loaded on to create the object
Disadvantages: easily lead to waste of resources

public class Single{
    private static final Single instance = new Single();
    private Single(){
    }
    public static Single getInstance(){
        return instance;
    }
}

Static code blocks

public class Single{
    private Single(){
    }
    private static Single instance;
    static{
        instance = new Single();
    }
    public static Single getInstance(){
        return instance;
    }
}

2. lazy style

Thread unsafe manner, the following code solves the lazy loading but the thread of insecurity, when thread A judge success but lost the cpu then judged by another thread B, then there will be multiple instances

class Single{
    private static Single instance;
    private Single(){
    }
    public static Single getInstance(){
        if(instance == null){
            instance = new Single();
        }
        return instance;
    }
}

Join synchronized to solve the problem of thread synchronization
Cons: After each thread must come in a thread synchronization In making this judgment, inefficient

public class Single{
    private static Single instance;
    private Single(){
    }
    public static synchronized Single getInstance(){
        if(instance == null){
            instance = new Single();
        }
        return instance;
    }
}

Double check the way (recommended), which addresses the lazy loading and improved efficiency

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

3. static inner class way (recommended)

Here when calling getInstance method will load the static class, and jvm loaded class is thread safe, when classloading other threads can not enter, thus avoiding thread safe here and implemented lazy loading

public class Single{
    private Single(){
    }
    private static class Singleton{
        private static final Single instance = new Single();
    }
    public static Single getInstance(){
        return Singleton.instance;
    }

}

4. Use the enumeration can solve thread safety, and prevent deserialization create objects (highly recommended)

enum  Single{
   INSTACE;
   public void test(){
       System.out.println("测试代码");
   }

}
Published 47 original articles · won praise 6 · views 2191

Guess you like

Origin blog.csdn.net/weixin_44467251/article/details/102766749
Recommended