Preliminary study of software design pattern

Keywords: Java

Software Design Pattern, also known as design pattern, is a summary of code design experience that is repeatedly used, known by most people, classified and catalogued. It describes some recurring problems in the software design process and the solutions to the problems.
It is a series of routines to solve specific problems. It has certain universality and can be used repeatedly.
Its purpose is to improve the reusability, readability and reliability of the code.

1, Singleton mode

1. What is singleton mode?

Definition of Singleton pattern: a pattern in which a class has only one instance and the class can create the instance itself.

2. What are the implementation methods of singleton mode?

Common implementation methods include lazy mode, hungry mode, double check lock, static internal class, enumeration and so on

2.1 lazy mode

/**
 * @author hz
 * @version 1.0
 */
public class Singleton {
    private static Singleton instance = null;
    private Singleton(){}
    public static Singleton getInstance(){
        //If it has not been instantiated, instantiate one and return
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }
}

In this code, thread safety is not considered, so there may still be multiple instances of parameters, so the thread safety problem needs to be solved to obtain the optimized version of lazy mode:

/**
 * @author hz
 * @version 1.0
 */
public class Singleton {
    private static Singleton instance = null;
    private Singleton(){}
    public static synchronized Singleton getInstance(){
        //If it has not been instantiated, instantiate one and return
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }
}

The keyword synchronized is used to ensure the thread safety of the getInstance method, but this method has great disadvantages. All threads need to wait in line after arriving at the method, so the performance loss is very large. This treatment solves the thread safety problem and does not solve the efficiency problem.
Lazy mode places the instantiation time when it needs to be used, that is, "delayed loading", which can avoid instantiating instances that may not be used during loading, but we need to spend energy to solve the problem of thread safety.

2.2 hungry Han mode

/**
 * @author hz
 * @version 1.0
 */
public class Singleton {
    //When the class is loaded, instance already points to an instance
    private static Singleton instance = new Singleton();
    private Singleton(){}
    public static Singleton getInstance(){
        return instance;
    }
}

Compared with the lazy mode, the hungry mode already has an instance when the class is loaded. The disadvantage of the hungry mode is that many useless instances may be generated.
We don't see the synchronized keyword in the code. When loading classes, the JVM is single threaded, so we can ensure that there is only a single instance.

2.3 double check lock

/**
 * @author hz
 * @version 1.0
 */
public class Singleton {
    private static Singleton instance = null;
    private Singleton(){}
    public static Singleton getInstance(){
        if(instance == null){
            synchronized (Singleton.class){
                if(instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

Double check lock is also a kind of delayed loading, and better solves the problem of low efficiency in ensuring thread safety. Compare with the most original thread safety method, which locks the whole getInstance method, so you have to obtain the lock, release the lock, wait, etc. every time you call that method... And double check lock locks part of the code. If the check of the entry method is empty, it will enter the synchronization code block, which is obviously much more efficient.

2.4 static internal class

/**
 * @author hz
 * @version 1.0
 */
public class Singleton {
    private static class SingletonHolder{
        private static Singleton instance = new Singleton();
    }
    private Singleton(){}
    public static Singleton getInstance(){
        return SingletonHolder.instance;
    }
}

Static internal classes are the way to enjoy the convenience of class loading to ensure thread safety and delay loading.

The characteristics of Java static internal classes are: internal static classes will not be loaded when loading, but will be loaded when using. When used, class loading is thread safe, which perfectly achieves our expected effect.

2.5 enumeration

JDK 1.5 provides a new data type: enumeration.

/**
 * @author hz
 * @version 1.0
 */
public enum Singleton {
    INSTANCE;
}

Enumeration provides an elegant way to replace a large number of static final variables. Here, we also use the enumeration feature to realize the singleton mode. The external call has changed from Singleton.getInstance to Singleton.INSTANCE.

3. Characteristics of singleton mode

1) . singleton mode has only one instance object;
2) . the singleton object must be created by the singleton class;
3) . the singleton class provides a global access point for accessing the singleton.

4. Advantages and disadvantages of singleton mode

advantage:

1) The singleton mode can ensure that there is only one instance in the memory and reduce the memory overhead.
2) . multiple occupation of resources can be avoided.
3) . set global access points in singleton mode to optimize and share resource access.

Disadvantages:

1) . the singleton mode generally has no interface and is difficult to expand. If you want to expand, there is no second way except to modify the original code, which violates the opening and closing principle.
2) In concurrent testing, singleton mode is not conducive to code debugging. During debugging, if the code in the singleton is not executed, a new object cannot be simulated.
3) The function code of singleton mode is usually written in a class. If the function design is unreasonable, it is easy to violate the principle of single responsibility.

5. Application scenario of singleton mode:

The application scenarios of singleton mode mainly include the following aspects:

1) For some classes that need to be created frequently, using singleton can reduce the memory pressure of the system and reduce GC.
2) When a class requires only one object to be generated
3) . some classes occupy more resources when creating instances, or instantiation takes a long time and is often used.
4) When a class needs to be instantiated frequently and the created object is destroyed frequently
5) . objects that frequently access databases or files.
6) For some control hardware level operations, or from the system point of view, they should be single control logic operations. If there are multiple instances, the system will be completely disordered.
7) When objects need to be shared. Since singleton mode allows only one object to be created, sharing the object can save memory and speed up object access.

2, Factory mode

1. What is the factory model?

Define a factory interface for creating product objects, and postpone the actual creation of product objects to specific sub factory classes. This meets the requirement of "separation of creation and use" in the creation mode. In the actual development, we can try to use factory pattern instead of complex objects.

2. Implementation mode of factory mode

There are three different implementations of factory pattern: simple factory pattern, factory method pattern and abstract factory pattern.

2.1 simple factory mode

We call the created object "product" and the object that creates the product "factory". If there are not many products to be created, only one factory class can be completed. This mode is called "simple factory mode".
The method of creating an instance in the simple factory pattern is usually static.
Therefore, Simple Factory Pattern is also called Static Factory Method Pattern.

2.1.1 composition of simple factory mode

Simple factory: it is the core of the simple factory pattern and is responsible for implementing the internal logic of creating all instances. The method of creating product class of factory class can be directly called by the outside world to create the required product object.
Abstract Product: it is the parent class of all objects created by a simple factory and is responsible for describing the common interface shared by all instances.
Concrete product: it is the creation target of simple factory mode.

Draw structure diagram:

2.1.2 java code representation

/**
 * @author hz
 * @version 1.0
 */
public class Client {
    //Abstract product
    public interface Product {
        void show();
    }
    //Specific product: ProductA
    static class ConcreteProduct1 implements Product {
        public void show() {
            System.out.println("Specific product 1 display...");
        }
    }
    //Specific product: ProductB
    static class ConcreteProduct2 implements Product {
        public void show() {
            System.out.println("Specific product 2 display...");
        }
    }
    final class Const {
        static final int PRODUCT_A = 0;
        static final int PRODUCT_B = 1;
        static final int PRODUCT_C = 2;
    }
    static class SimpleFactory {
        public static Product makeProduct(int kind) {
            switch (kind) {
                case Const.PRODUCT_A:
                    return new ConcreteProduct1();
                case Const.PRODUCT_B:
                    return new ConcreteProduct2();
            }
            return null;
        }
    }
}

2.1.3 advantages and disadvantages of simple factory mode

advantage:

1) The factory class contains the necessary logical judgment to decide when to create an instance of which product. The client can avoid the responsibility of directly creating product objects and easily create corresponding products. The responsibilities of the factory and products are clearly distinguished.
2) . the client does not need to know the class name of the specific product created, but only needs to know the parameters.
3) . you can also import a configuration file to replace and add new specific product classes without modifying the client code.

Disadvantages:

1) The factory class of simple factory mode is single, which is responsible for the creation of all products. The responsibility is too heavy. Once it is abnormal, the whole system will be affected. Moreover, the factory class code will be very bloated and violate the principle of high aggregation.
2) . using simple factory mode will increase the number of classes in the system, and increase the complexity and understanding difficulty of the system
3) It is difficult to expand the system. Once new products are added, the factory logic has to be modified. When there are many product types, the logic may be too complex
4) The static factory method is used in the simple factory mode, which makes the factory role unable to form an inheritance based hierarchical structure.

2.2 factory method mode

The "factory method mode" is a further abstraction of the simple factory mode. Its advantage is that the system can introduce new products without modifying the original code, that is, it meets the opening and closing principle.

2.2.1 composition of plant method mode

Abstract Factory: it provides an interface for creating products, through which the caller accesses the factory method newProduct() of a specific factory to create products.
Concrete factory: it mainly implements the abstract methods in the abstract factory and completes the creation of specific products.
Abstract Product: it defines the specification of the Product and describes the main characteristics and functions of the Product.
Concrete product: it implements the interface defined by the abstract product role, which is created by the specific factory and corresponds to the specific factory one by one.

The structure drawing is as follows:

2.2.2 java code representation

/**
 * @author hz
 * @version 1.0
 */
public class AbstractFactoryTest {
    public static void main(String[] args) {
        try {
            Product a;
            AbstractFactory af;
            af = (AbstractFactory) ReadXML.getObject();
            //Abstract factory contents are put into external configuration files, such as xml/properties, and loaded through I/O streams to create abstract factories
            a = af.newProduct();
            a.show();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
//Abstract product: provides the interface of the product
interface Product {
    public void show();
}
//Concrete product 1: implement abstract methods in abstract products
class ConcreteProduct1 implements Product {
    public void show() {
        System.out.println("Specific product 1 display...");
    }
}
//Concrete product 2: implement abstract methods in abstract products
class ConcreteProduct2 implements Product {
    public void show() {
        System.out.println("Specific product 2 display...");
    }
}
//Abstract factory: provides the generation method of factory products
interface AbstractFactory {
    public Product newProduct();
}
//Specific factory 1: the generation method of factory products is realized
class ConcreteFactory1 implements AbstractFactory {
    public Product newProduct() {
        System.out.println("Specific factory 1 generation-->Specific products 1...");
        return new ConcreteProduct1();
    }
}
//Specific factory 2: the generation method of factory products is realized
class ConcreteFactory2 implements AbstractFactory {
    public Product newProduct() {
        System.out.println("Specific plant 2 generation-->Specific products 2...");
        return new ConcreteProduct2();
    }
}
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
/**
 * @author hz
 * @version 1.0
 */
public class ReadXML {
    //This method is used to extract the specific class name from the XML configuration file and return an instance object
    public static Object getObject() {
        try {
            //Create document object
            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dFactory.newDocumentBuilder();
            Document doc;
            doc = builder.parse(new File("src/FactoryMethod/config1.xml"));
            //Gets the text node containing the class name
            NodeList nl = doc.getElementsByTagName("className");
            Node classNode = nl.item(0).getFirstChild();
            String cName = "FactoryMethod." + classNode.getNodeValue();
            //System.out.println("new class name:" + cName);
            //Generate an instance object from the class name and return it
            Class<?> c = Class.forName(cName);
            Object obj = c.newInstance();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}

2.2.3 advantages and disadvantages of factory method mode

advantage:

1) Users only need to know the name of the specific factory to get the desired product without knowing the specific creation process of the product.
2) The flexibility is enhanced. For the creation of new products, you only need to write one more corresponding factory class.
3) A typical decoupling framework. The high-level module only needs to know the abstract class of the product, does not need to care about other implementation classes, and meets the Demeter rule, dependency inversion principle and Richter substitution principle.

Disadvantages:

1) The number of classes is easy to be too many, which increases the complexity
2) It increases the abstraction and understanding difficulty of the system
3) Abstract products can only produce one product, which can be solved by using abstract factory mode.

2.3 abstract factory mode

Abstract factory pattern definition: it provides an interface for access classes to create a group of related or interdependent objects, and the access class can obtain the pattern structure of products of different levels of the same family without specifying the specific class of the product. Here are two concepts: same family and same level.

2.3.1 composition of abstract factory pattern

1) Abstract Factory: it provides an interface for creating products. It contains multiple methods newProduct() for creating products, and can create multiple products of different levels.
2) Concrete Factory: it mainly implements multiple abstract methods in the abstract factory to complete the creation of specific products.
3) . abstract Product: defines the specification of the Product and describes the main characteristics and functions of the Product. The abstract factory pattern has multiple Abstract products.
4) Concrete product: it implements the interface defined by the abstract product role and is created by the concrete factory. It has a many-to-one relationship with the concrete factory.

Draw structure diagram:

2.3.2 java code representation

/**
 * @author  hz
 * @version 1.0
 */
public class FarmTest {
    public static void main(String[] args) {
        try {
            Farm f;
            Animal a;
            Plant p;
            //Read the corresponding configuration information for the production plant
            f = (Farm) ReadXML.getObject();
            a = f.newAnimal();
            p = f.newPlant();
            a.show();
            p.show();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
//Abstract products: Animals
interface Animal {
    public void show();
}
//Specific products: Horses
class Horse implements Animal {
    public Horse() {
        System.out.println("Generation of specific horses");
    }
    public void show() {
        System.out.println("Perform corresponding operations for horses");
    }
}
//Specific products: Cattle
class Cattle implements Animal {

    public Cattle() {
        //Generation of specific cattle
        System.out.println("Generation of specific cattle");
    }
    public void show() {
        System.out.println("Perform corresponding operations for horses");
    }
}
//Abstract products: Plants
interface Plant {
    public void show();
}
//Specific products: Fruits
class Fruitage implements Plant {

    public Fruitage() {
        System.out.println("Specific fruit generation");
    }
    public void show() {
        System.out.println("Perform corresponding operations for fruits");
    }
}
//Specific products: Vegetables
class Vegetables implements Plant {
    public Vegetables() {
        System.out.println("Specific vegetable generation");
    }
    public void show() {
        System.out.println("Perform the corresponding operations of vegetables");
    }
}
//Abstract factory: Farm class
interface Farm {
    public Animal newAnimal();
    public Plant newPlant();
}
//Specific factory: Farm 1
class SGfarm implements Farm {
    public Animal newAnimal() {
        System.out.println("A new cow is born!");
        return new Cattle();
    }
    public Plant newPlant() {
        System.out.println("Vegetables grow!");
        return new Vegetables();
    }
}
//Specific factory: Farm 2
class SRfarm implements Farm {
    public Animal newAnimal() {
        System.out.println("The new horse was born!");
        return new Horse();
    }
    public Plant newPlant() {
        System.out.println("Fruit grows!");
        return new Fruitage();
    }
}
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.File;

/**
 * @author hz
 * @version 1.0
 */
public class ReadXML2 {
    public static Object getObject() {
        try {
            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dFactory.newDocumentBuilder();
            Document doc;
            doc = builder.parse(new File("src/AbstractFactory/config.xml"));
            NodeList nl = doc.getElementsByTagName("className");
            Node classNode = nl.item(0).getFirstChild();
            String cName = "AbstractFactory." + classNode.getNodeValue();
            System.out.println("New class name:" + cName);
            Class<?> c = Class.forName(cName);
            Object obj = c.newInstance();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

2.3.3 advantages and disadvantages of abstract factory mode

advantage

1) . the multi-level products associated in the product family can be managed together within the class, instead of introducing multiple new classes for management.
2) When a product family is required, the abstract factory can ensure that the client always uses only the product group of the same product.
3) The abstract factory enhances the scalability of the program. When adding a new product family, there is no need to modify the original code to meet the opening and closing principle.

shortcoming

When a new product needs to be added to the product family, all factory classes need to be modified. It increases the abstraction and understanding difficulty of the system.

2.3.4 application scenarios

1) When the objects to be created are a series of interrelated or interdependent product families, such as televisions, washing machines, air conditioners, etc. in electrical factories.
2) There are multiple product families in the system, but only one of them is used at a time. If someone only likes to wear clothes and shoes of a certain brand.
3) The class library of products is provided in the system, and the interfaces of all products are the same. The client does not depend on the creation details and internal structure of product instances.

summary

Singleton mode
In various design methods of singleton pattern, we use the characteristics of internal static classes and enumeration, so the foundation is very important. Singleton pattern is one of the design patterns, and design pattern is actually a further packaging of the insufficient language characteristics.
Factory mode
For the case of relatively few product types, consider using the simple factory mode. The client using the simple factory mode only needs to pass in the parameters of the factory class and does not need to care about the logic of how to create objects. It can easily create the required products.

For a product, the caller clearly knows which specific factory service should be used, instantiates the specific factory and produces a specific product, then we can adopt the factory method mode.
Or we just need a product and don't want to know or need to know which factory produces it. They instantiate a specific factory according to the current system situation and return it to the user. This decision-making process is transparent to the user. We can also choose the factory method mode.

The extension of abstract factory mode has a certain inclination of "opening and closing principle":
When adding a new product family, you only need to add a new specific factory without modifying the original code to meet the opening and closing principle.
When a new type of product needs to be added to the product family, all factory classes need to be modified, which does not meet the opening and closing principle.
On the other hand, when there is only one product with hierarchical structure in the system, the abstract factory mode will degenerate to the factory method mode. The factory mode is used in many occasions in real life. Whether to use the factory method mode or the abstract factory mode depends on our actual situation.
reference:
Design mode - single case mode - by Cadbury
JAVA design pattern series - Factory Pattern - by Cadbury
Design pattern series - Abstract Factory Pattern - by Cadbury

Posted by RalphOrange on Sun, 19 Sep 2021 03:01:08 -0700