Singleton design pattern of articles (a)

Singleton is one of the simplest design pattern. When only one instance of a class, we can use this model, such as database connections, can improve efficiency and avoid waste of resources.

Singleton design pattern can be divided into two modes lazy and hungry man.

1, hungry man:

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

It is called starving style, because at the time the class is loaded, it initializes the only instance of need. This is the simplest implementation, private constructor property ensures that there will be no such second instance. Because class time is loaded, it has been the case, so this implementation is thread-safe.

2, lazy style

public class Singleton2 {
    private Singleton2(){}
    private static Singleton2 singleton2 = null;
    public static Singleton2 getInstance(){
        if(singleton2 == null){
            singleton2 = new Singleton2();
        }
        return singleton2;
    }
}

Chinese-style different from the hungry, lazy man only when in use, will produce a unique instance. But therefore also had another problem, modify singleton2 when accessing objects may be affected and the number of access speed, and the emergence of multiple instances of the situation, so that is not thread safe.

3, lazy formula 2.0

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

To obtain an instance method with synchronization, making synchronization function, exclusive access to internal resources, we can solve the problem of thread-safe. But new problems have cropped up, but also need to address it, and that is efficiency.

4, lazy Formula 3.0

public class Singleton2 {
    private Singleton2(){}
    private static Singleton2 singleton2 = null;
    public static Singleton2 getInstance(){
        if(singleton2 == null){
            synchronized (Singleton2.class){
                if(singleton2 == null){
                    singleton2 = new Singleton2();
                }
            }
        }
        return singleton2;
    }
}

注意到,如果使用同步函数,那么将会对内部所有代码上锁,意味着每次调用该实例,都要判断一下,效率很低。然而真正要考虑线程安全的地方仅仅是初始化实例的时候。所以为了提高效率,在锁代码块之前,先判断一下需不需要new实例,即是不是第一次访问。这样,大部分情况下不需要进同步块,提高了效率。

如有错误,欢迎批评指正。

Guess you like

Origin www.cnblogs.com/phdeblog/p/10972967.html