Hello everyone, I am Wolf King, a programmer who loves playing ball

This is the sixth part of the design Patterns series, which lets us look at a single pattern


1, an overview of the

A singleton pattern is a creative design pattern that allows you to guarantee that there is only one instance of a class and provide a global node to access that instance.

The singleton pattern solves two problems:

1) Ensure that there is only one instance of a class

2) Provide a global access node for the instance.

2. Application Scenario

1) If a class in the program has only one instance available for all clients, use the singleton pattern. 2) If you need more control over global variables, use the singleton pattern.

3, the instance,

The implementation of singletons

1) Hungry man mode

Thread safe, class loading is completed, instantiation is completed, simple and practical, recommended.

public class Singleton {

    private final static Singleton instance = new Singleton();

    public static Singleton getInstance(a) {
        return instance;
    }

    private Singleton(a) {}}Copy the code

2) Lazy mode (thread unsafe)

Instantiated when used, but not thread safe.

public class Singleton {

    private static Singleton instance;

    public static Singleton getInstance(a) {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

    private Singleton(a) {}}Copy the code

3) Lazy mode (thread safe)

It is loaded when it is used and thread-safe with Synchronized. In the case of multithreading, a large number of threads are blocked and the efficiency is reduced.

public class Singleton {

    private static Singleton instance;

    public static synchronized Singleton getInstance(a) {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

    private Singleton(a) {}}Copy the code

4) Slacker Mode (DCL)

In the case of low efficiency above, the number of synchronized code blocks is reduced, but there is the problem of thread insecurity. In the case of multithreading, there will be multiple instances.

public class Singleton {

    private static Singleton instance;

    public static Singleton getInstance(a) {
       if (instance == null) {
              synchronized (Singleton.class) {
                  instance = newSingleton(); }}return instance;
    }

    private Singleton(a) {}}Copy the code

Introduce the double-checked locking DCL, note the use of the volatile keyword here to prevent the problem of instruction reordering. When the bean is semi-initialized, instruction reordering can cause semi-initialized objects to be used.

public class Singleton {

    /** * Volatile to resolve order reorder issues */
    private static volatile Singleton instance;

    public static Singleton getInstance(a) {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = newSingleton(); }}}return instance;
    }
    private Singleton(a) {}}Copy the code

5) Static inner classes

The JVM guarantees singletons because classes are only loaded once when the JVM loads them. Inner classes are not loaded until they are used.

Internal static classes are not automatically initialized. Static inner classes are loaded only when a static inner class's methods, static fields, or constructors are called
public class Singleton {

    private static class SingletonHolder {
        private static Singleton instance = new Singleton();
    }

    public static Singleton getInstance(a) {
        return SingletonHolder.instance;
    }

    private Singleton(a) {}}Copy the code

6) enumeration

Implementing the singleton pattern has three main features:

1. Privatization of construction methods;

2. Privatize instantiated variable references;

3. The methods for obtaining instances are common. The exception is enumeration.

Benefits of using enumerations:

1. Avoid reflex attacks.

2. Avoid deserialization.

public enum Singleton {

    INSTANCE;
    
    public void doSomeThing(a){
        System.out.println("this is singleton by enum"); }}Copy the code

4, summarize

Advantages:

1) There is only one instance of a class.

2) Points to the global access node of the instance.

3) Will be initialized only once (the first access or or the project is created upon startup).

Disadvantages:

1) Violation of single responsibility, because it guarantees that a class is instantiated only once, while providing global access nodes.

2) Multithreaded case should be processed separately, to prevent the creation of multiple singleton objects.

VX search: Wolf king programming white prostitute a large number of learning resources!