Design Pattern: Singleton Pattern

Singleton pattern:

Definition:
Ensure that a class has only one instance, and instantiate itself and provide this instance to the entire system or provide a global access point to it

Usage scenarios:
Make sure that a class has one and only one object scenario, avoid generating multiple objects that consume too much resources, or a certain type of object should have and only one. For example, creating an object needs to consume too many resources.
If you want to access resources such as IO and database, you should consider using the singleton pattern

Implementation process:
1. The constructor is not open to the outside world, usually Private
2. Returns the singleton object through a static method or enumeration
3. Ensure that there is only one object of the singleton class, especially in the case of multi-threading
4 . , to ensure that the singleton object is not rebuilt when deserializing

Six ways to write the singleton mode:
1.
Hungry mode

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

    private Singleton() {
    }

    public static Singleton getSingletonInstance() {
        return singleton;
    }
}

Advantages:
1. Initialization during class loading, slow class loading and fast object acquisition
2. Based on the class loading mechanism, avoiding multi-threaded synchronization problems
Disadvantages
: 1. Complete initialization during class loading, not lazy loading The effect
2, has never been used, it will cause a waste of memory

2.
Lazy mode (thread unsafe)

public class Singleton {
    private static Singleton singleton;

    private Singleton() {
    }

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

Advantages:
Lazy people are unfamiliar with declaring a static object, which is initialized when the user calls it for the first time, saving resources.
Disadvantages
: The first load needs to be instantiated, the response is slightly slower, and it is not safe in multi-threading
.

3
Lazy mode (thread safety)

public class Singleton {
    private static Singleton singleton;

    private Singleton() {
    }

    public static synchronized Singleton getSingletonInstance() {
        if (singleton==null){
            singleton=new Singleton();
        }
        return singleton;
    }
}

Advantages : suitable for multi-threading
Disadvantages : synchronization is required every time an instance is obtained, resulting in unnecessary synchronization overhead

4
Double Check Mode (DCL)

public class Singleton {
    private volatile static Singleton singleton;

    private Singleton() {
    }

    public static Singleton getSingletonInstance() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

Advantages :
two empty judgments, the first time is for unnecessary synchronization, the second time to determine whether the instance is null, the resource rate is high, the efficiency is high, and the instance is initialized when the instance is obtained for the first time
Overall : to a certain extent, the resource is solved
Disadvantages : volatile affects performance, the first load is slower, and there are certain defects in the case of high concurrency

5
Static inner class singleton

public class Singleton {

    private Singleton() {
    }
    public static Singleton getSingletonInstance() {
       return  SingletonHolder.singletonA;
    }
    private static class SingletonHolder{
        private static  final  Singleton singletonA=new Singleton();
    }
}

Advantages : SingletonA is not initialized when the Singleton class is loaded for the first time. Only when the getSingletonInstance method is called for the first time, the virtual machine loads the SingletonHolder and initializes singletonA, which not only ensures thread safety, but also ensures the uniqueness of the Singleton class.

6
Enumeration Singleton

public enum Singleton {
    SINGLETON;
    public void doSomeThing() {
    }
}

The default enumeration instance creation is thread-safe and is a singleton in any case. The advantage is simplicity and low usage.

Remarks : Write a singleton instance object to disk and read it back to obtain an instance
to prevent the singleton mode from being deserialized, plus the sentence
private Object readResole()throws ObjectStreamExceptioniuon{
retuen singleton;
}

Summarize:

Advantages :
1. Since the singleton pattern has only one instance in memory, it reduces the memory overhead, especially when an object needs to be created and destroyed frequently, and the common or destruction performance cannot be optimized, the advantage of the singleton pattern is very Obviously
2. Since the singleton mode only generates one instance, the performance overhead of the system is reduced. When the generation of an object requires more resources, such as reading the configuration and generating other dependent objects, you can start the application by starting the application. 3. Singleton
mode can avoid multiple occupation of resources
4. Singleton mode can set global access points, optimize and share resource access

Disadvantages :
1. The singleton mode generally has no interface, and it is difficult to expand.
2. If the singleton mode holds Context, it is easy to cause memory leaks. Pass getApplacioton Context

Guess you like

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