Common Design Patterns

There are 23 design patterns.

1. Factory pattern: The factory pattern is to create instances of other classes by a specific class. The parent class is the same, and the parent class is specific.

Second, the factory method pattern: The factory method pattern is that there is an abstract parent class to define the public interface, and the subclass is responsible for generating specific objects. The cemetery for this is to delay the instantiation of the class to the subclass to complete.

3. Singleton mode: There are three types of singleton mode, and the singleton mode must have three characteristics. 1. A singleton class can have only one instance 2. A singleton class must create its own unique instance by itself 3. A singleton class must provide this instance to all other objects

  1. Sloth

  

public class Singleton {  
    private Singleton() {}  
    private static Singleton single=null;  
    //静态工厂方法   
    public static Singleton getInstance() {  
         if (single == null) {    
             single = new Singleton();  
         }    
        return single;  
    }  
}  

  The implementation of lazy singleton does not consider the issue of thread safety. It is not thread-safe. To achieve thread safety, a synchronization lock needs to be added . Better to use static inner classes.

  2. Hungry man

  

public class Singleton1 {  
    private Singleton1() {}  
    private static final Singleton1 single = new Singleton1(); 
    public static Singleton1 getInstance() {  
        return single;  
    }  
}  

  Hungry-style has created a static object for the system to use when the class is created, and will not change it in the future, so it is inherently thread-safe.

  3. Registration (understanding)

Guess you like

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