[Sword refers to offer] Interview question 02: Implementing the Singleton pattern - 6 ways to implement

1. What is a design pattern

Reference Blog 1 , Blog 2 , Blog 3 , Blog 4
1. What are design patterns? Design patterns are a set of code design experiences that
have been used repeatedly, known to most people, and categorized and catalogued . In particular, a pattern is not a code, but a general solution which is a method used by many people. 2. Why use design patterns and what problems can they help us solve? Design patterns make it easier to reuse code, make the code easier for others to understand, and ensure the reliability of the code.

Second, what is the singleton pattern

1. Design patterns are divided into three categories: creational patterns, structural patterns, and behavioral patterns. The singleton pattern is one of the creational patterns. The singleton pattern requires that there is only one instance when the system is running. Objects;
application examples : task manager of windows, recycle bin, configuration objects of web applications, printers, etc.

3. Features of the singleton pattern

  1. The singleton pattern can only have one instance object;
  2. A singleton class must create its own unique instance;
  3. A singleton class must provide this instance to other objects.

Fourth, the realization of the singleton pattern

According to the above 3 basic requirements, you can know the design points:
1. The singleton pattern can only have one instance object - you need to customize the private constructor, so that the constructor will not be called
2. The singleton class must create its own The only instance - there must be an object instance inside the class
3. The singleton class must provide this instance to other objects - the function with public modification inside the class returns the internal object instance


  1. lazy mode
public class Singleton{
    private static Singleton instance = null;

    private Singleton(){    }

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

As above, by providing a static object instance, use the private permission constructor and getInstance() method to give the visitor a singleton. The reason why it is called lazy mode is because this method can be very obvious that it must first determine whether it is null before loading.
The disadvantage is that thread , and there may be a problem of multiple visitors accessing at the same time and constructing multiple objects at the same time;
for the problem of thread insecurity in the lazy mode, a lock is added before the getInstance() method, so there is a problem The second implementation.
2. Thread-safe lazy mode

public class Singleton{
    private static Singleton instance = null;

    private Singleton(){    }

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

By modifying the getInstance() method with the synchronized keyword, the problem of access conflicts of multiple threads is solved, but it will introduce unnecessary blocking:
* When multiple threads call the getInstance() method, first allow one thread to call, and other threads to wait. However, when the first thread is called, the singleton has been created, and the following threads are still waiting when the second thread is called. This kind of waiting is meaningless, which will cause blocking and reduce efficiency.
3. Double-checked lazy mode

public class Singleton{
    private volatile static Singleton5 instance = null;

    private Singleton(){    }

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

Use the lazy mode of double validation to check if the instance is null before waiting.
4. Static class internal loading

public class Singleton{
    private Singleton(){    }

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

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

The advantage of using inner classes is that static inner classes are only loaded when the getInstance() method is called. When the getInstance() method is called for the first time, an instance instance will be created, and then the instance will be returned only when needed. , which implements on-demand creation and is thread-safe.
5. Implemented by enumeration If you do
n't understand it, you can check it yourself in the blog referenced earlier.

other


  1. Hungry man mode Corresponding to the lazy man mode is the "hungry man mode", the code is as follows:
public class Singleton{
    private static Singleton instance = new Singleton();

    private Singleton(){    }

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

When the class initialization is executed to the static property, the resource is allocated, and then it can be accessed directly through the method. Obviously, this method does not have the lazy loading effect of the lazy mode. Compared with the lazy mode, it only has one more memory resident.

Guess you like

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