Software design pattern learning abstract factory pattern

Abstract factory pattern

Abstract factory pattern is one of the common construction design patterns, which is more abstract than factory method pattern. In the factory method mode, the specific factory only produces one specific product, but in the abstract factory mode, the specific factory can produce a group of related specific products, such a group of products is called product family, and each product in the product family belongs to a product inheritance hierarchy.


Mode motivation

Sometimes we need a factory to provide multiple product objects, rather than a single product object, such as an electrical equipment factory, which can produce TV sets, refrigerators, air conditioners and other equipment, rather than just some kind of electrical appliances. In order to understand the abstract factory pattern more clearly, two concepts are introduced:

  1. Product grade structure: Product grade structure is the inheritance structure of products. For example, an abstract class is TV, and its sub classes are Haier TV, TCL TV, etc. between abstract TV and specific brand TV, a product grade structure is formed.

  2. Product family: refers to a group of products produced by the same factory and located in different product hierarchy. For example, if Haier electric appliance factory produces Haier TV and Haier refrigerator, they are the same product family and located in different product hierarchy.

    [external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-KyRte5v6-1583586756775)(C:\Users\LENOVO\AppData\Roaming\Typora\typora-user-images\image-20200307152957643.png))

Abstract factory pattern is needed when the specific products produced by the factory provided by the system are not a simple object, but multiple concrete products belonging to different types in different product hierarchy.


Schema definition

Provides an interface to create a series of related or interdependent objects without specifying their specific classes.

Pattern structure

  1. Abstract factory

    Abstract factory is used to declare the methods to produce abstract products. In an abstract factory, a group of methods can be defined. Each method corresponds to a product hierarchy

  2. ConcreteFactory (specific factory)

    The concrete factory implements the method of producing Abstract products declared by the abstract factory, and produces a group of concrete products. These products form a product family, and each product is located in a product hierarchy.

  3. Abstractproduct (abstract product)

    Abstract products declare interfaces for each product, and define abstract business methods of products in abstract products

  4. Concrete product

    Specific products define specific product objects produced by specific factories, and implement the business methods defined in the abstract product interface.


Electrical factory of abstract factory model

  1. Example illustrate

    An electrical factory can produce many types of electrical appliances, such as Haier TV, Haier air conditioner, etc., TCL TV, TCL air conditioner, etc., the same brand of electrical appliances constitute a product family, and the same type of electrical appliances constitute a product grade structure.

  2. Example code and explanation

    1. Abstract product class Television

      public interface Television {
      
          void play();
      }
      
    2. Haier television (Haier TV)

      public class HairTelevision implements Television {
      
          @Override
          public void play() {
      
              System.out.println("Haier TV is playing......");
          }
      }
      
    3. Specific product TCL television

      public class TCLTelevision implements Television {
      
          @Override
          public void play() {
      
              System.out.println("TCL TV playing.......");
          }
      }
      
    4. Abstract product class aircondition

      public interface AirConditioner {
      
          void changeTemperature();
      }
      
    5. Haier air conditioner (Haier air conditioner)

      public class HairAirConditioner implements AirConditioner {
      
          @Override
          public void changeTemperature() {
              System.out.println("Haier air conditioning temperature changing.....");
          }
      }
      
    6. Specific product class tclaircondition (TCL air conditioning class)

      public class TCLAirConditioner implements AirConditioner {
      
          @Override
          public void changeTemperature() {
              System.out.println("TCL Air conditioning temperature changing......");
          }
      }
      
    7. Abstract factory class

      public interface EFactory {
      
          Television produceTelevision();
         
          AirConditioner produceAirConditioner();
         }
      
    8. Specific factory class hairfactory (Haier factory class)

      public class HairFactory implements EFactory {
      
          @Override
          public Television produceTelevision() {
              return new HairTelevision();
          }
      
          @Override
          public AirConditioner produceAirConditioner() {
              return new HairAirConditioner();
          }
      }
      
    9. Specific factory class TCLPFactory

      public class TCLFactory implements EFactory {
      
          @Override
          public Television produceTelevision() {
              return new TCLTelevision();
          }
      
       @Override
          public AirConditioner produceAirConditioner() {
           return new TCLAirConditioner();
          }
      }
      
    10. XML operation tool class

      public class XMLUtil {
         
             public static Object getBean() throws Exception {
         
                 //Create parser factory
                 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
              //Create parser
                 DocumentBuilder builder = builderFactory.newDocumentBuilder();
              //Get document
                 Document document = builder.parse("configPhone.xml");
              //Get the text node containing the brand name
                 NodeList brandNameList = document.getElementsByTagName("factoryName");
              Node classNode = brandNameList.item(0).getFirstChild();
                 String factoryName = classNode.getNodeValue().trim();
      
         //        System.out.println(factoryName);
      
                 Class c = Class.forName("com.abstractFactory." + factoryName);
                 Object o = c.newInstance();
                 return o;
             }
         }
      
    11. configuration file

      <?xml version="1.0" encoding="UTF-8" ?>
      <configuration>
         <factoryName>HairFactory</factoryName>
      </configuration>
      
    12. Test class

      public class Test {
      
          public static void main(String[] args) throws Exception {
      
              EFactory factory = (EFactory) XMLUtil.getBean();
      
              Television television = factory.produceTelevision();
      
              television.play();
      
              AirConditioner airConditioner = factory.produceAirConditioner();
      
              airConditioner.changeTemperature();
          }
      }
      
    13. Result analysis

      If the content in the node is set to HairFactory in the configuration file, the output is as follows:

      If the content in the node is set to TCLFactory in the configuration file, the output result is as follows:

      If you need to add a new brand of electrical appliances, that is, add a new product family. For example, add Hisense TV and Hisense air conditioner, you only need to add a specific factory correspondingly, and then change the specific factory class name in the configuration file to the new factory class name. The original code does not need to be modified. But if we want to add new products, such as new washing machines for electrical products, abstract factories need to declare a method to produce washing machines, and all specific factory classes need to implement this method, which will lead to the system no longer complying with the opening and closing principles.

Published 27 original articles, won praise 12, visited 8410
Private letter follow

Tags: xml encoding

Posted on Sat, 07 Mar 2020 05:33:25 -0800 by duncanwilkie