Singleton design pattern 6 kinds of common design patterns

Design Singleton design pattern in accordance with the time of creation into hungry (relatively urgent use) Chinese-style, lazy (lazy only when needed to create) Chinese-style

Common form of starving formula

  1. Instantiated directly (visual comparison profile)
  2. An enumerated (the most simple)
  3. Starving formula static block of code (for example of the complex)

Common form of lazy style

  1. Thread-safe (suitable for single-threaded)
  2. Thread-safe (suitable for multi-threaded)
  3. Static inner classes (for the multi-threaded)

 ① starving formula instantiated directly Sample Code

public class Singleton1 {
    public static final Singleton1 INSTANCE=new Singleton1();
    private Singleton1(){
        
    }
}

② enumerated type

public enum  Singleton2 {
    INSTANCE
}

③ static code block

public class Singleton3 {
    public static final Singleton3 INSTANCE;
    static {
        INSTANCE=new Singleton3();
    }
    private Singleton3(){

    }
}

 

④ lazy style thread safe (for the single-threaded program)

public class Singleton4 {
    public static Singleton4 instance;

    private Singleton4(){

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

④ above way multithreading may cause security thread, multiple threads may have entered into if and then, perform new instantiation, resulting in more than one example of an object. The solution is to lock ensures that only one thread can enter if carried out new instantiation

⑤ thread-safe

public class Singleton5 {
    public static Singleton5 instance;
    private Singleton5() { }
    public static Singleton5 getInstance() {
        if (instance == null) {//提高效率加的判断
            synchronized (Singleton5.class) {
                if (instance == null) {
                    instance = new Singleton5();
                }
            }
        }
        return instance;
    }
}

⑥ static inner classes

Features static inner classes

  1. Creating INSTANCE instance of the object only when the internal class loading and initialization
  2. Static inner classes will not be automatically loaded and initialized with the outer class, jdk will go alone loaded and initialized
public class Singleton6 {
    private Singleton6(){ }
    private static class InnerClass{
        private static final Singleton6 INSTANCE=new Singleton6();
    }
    public static Singleton6 getInstance(){
        return InnerClass.INSTANCE;
    }
}

 

 

Published 242 original articles · won praise 13 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_41813208/article/details/103982098