Singleton pattern - creational design pattern

1. Hungry Chinese

  Pros: thread safe

  Cons: Loads instantly

2. Lazy Man

  Advantage: lazy loading

  Disadvantage: thread insecure (double lock mechanism can be used to ensure thread safety, but the call efficiency is low)

3. Internal type singleton mode, the first two are basically not used, because this includes the advantages of the first two

  Advantages: 1. Thread safety, 2. Lazy loading

code show as below:

copy code
package sington;

public class InnerSing {

    private InnerSing(){
    }

    public static InnerSing getIntance(){
        return InnerClass.instance;
    }

    private static class InnerClass {
        private static InnerSing instance = new InnerSing();
    }
}
copy code

 4. Enumeration class

  Advantages: The first three cannot avoid using reflection/serialization (that is, writing to the hard disk and then reading the hard disk to create objects) to create objects,

      The enumeration class can; (in fact, it can be written through the constructor code: object non-null judgment + error throwing can prevent reflection creation, and rewriting the readResolve() method can prevent deserialization from constructing one more object)

  Disadvantage: not lazy loading

code show as below:

copy code
package sington;

public enum EnumSing {

    INTANCE;

    public void function(){
        System.out.println("Specific execution method");
    }
    public static EnumSing getIntance(){
        return INTANCE;
    }
}
copy code

 

Guess you like

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