Factory mode of 23 design modes

Java technology debt 2022-06-24 07:28:17 阅读数:406

factorymodedesignmodes

Java Technical debt

Simple factory model

summary

in real life , Primitive society is self-sufficient ( No factories ), Small workshops in farming society ( Simple factory , Folk winery ), Industrial Revolution assembly line ( Factory method , Self marketing ), The modern industrial chain is the substitute factory ( Abstract factory , foxconn ).

The project code is also iterated from simple to complex step by step , But for the caller , But it's getting simpler .

In daily development , Where complex objects need to be generated , You can try to use factory mode instead of .

Be careful : The above complex object refers to the situation that too many constructor parameters of the class have an impact on the construction of the class , Because the construction of classes is too complex , If used directly in other business classes , The coupling between them is too heavy , Subsequent business changes , You need to make changes in any source code that references the class , It's time consuming just to find all the dependencies , Not to mention to modify one by one .

Definition of factory pattern

Define a factory interface for creating product objects , Postpone the actual creation of product objects to specific sub factory classes . This meets the requirements of the creation pattern “ Create separate from use ” Characteristics .

According to the actual business scenarios , What are the factory models 3 Different ways of implementation , Namely Simple factory model Factory method model and Abstract factory pattern .

We call the created object “ product ”, Call the object that creates the product “ factory ”. If there are not many products to create , Only one factory class can complete , This pattern is called “ Simple factory model ”.

The method of creating instances in simple factory mode is usually static (static) Method , So the simple factory model (Simple Factory Pattern) Also known as the static factory method pattern (Static Factory Method Pattern).

Simply speaking , The simple factory model has a specific factory class , You can generate many different products , It belongs to the creative design pattern . The simple factory model is not GoF 23 Among the design patterns .

For each product added in the simple factory model, a specific product class and a corresponding specific factory class are added , This increases the complexity of the system , Contrary to “ Opening and closing principle ”.

“ Factory method model ” It's a further abstraction of the simple factory pattern , The advantage is that the system can introduce new products without modifying the original code , That is to meet the opening and closing principle .

pros and cons

  1. advantage
    1. The factory class contains the necessary logical judgments , You can decide when to create an instance of which product . Clients can be exempt from the responsibility of creating product objects directly , It's very convenient to create corresponding products . The responsibilities of the factory and the product are clearly distinguished .
    2. The client does not need to know the class name of the specific product being created , Just know the parameters .
    3. You can also import configuration files , Replace and add new specific product classes without modifying the client code .
  2. shortcoming
    1. The factory class of simple factory mode is single , Responsible for the creation of all products , Too much responsibility , Once abnormal , The whole system will be affected . And the factory class code will be very bloated , Against the principle of high aggregation .
    2. Using the simple factory pattern will increase the number of classes in the system ( Introduce a new factory class ), Increase the complexity and understanding of the system
    3. Difficulty in system expansion , Once new products are added, the factory logic has to be modified , When there are many types of products , It may make the logic too complicated
    4. Simple factory mode uses static Factory method , Causes the factory role to fail to form inheritance based hierarchy .

Application scenarios

For a relatively small number of products , Consider the simple factory model . Clients using the simple factory pattern only need to pass in the parameters of the factory class , You don't need to care about the logic of how to create objects , It's easy to create the products you need .

The structure and implementation of patterns

The main roles of the simple factory model are as follows :

  • Simple factory (SimpleFactory): It's the core of the simple factory model , Responsible for implementing the internal logic of creating all instances . The method of creating product class of factory class can be called directly by the outside world , Create the required product objects .
  • Abstract product (Product): Is the parent of all objects created by the simple factory , Responsible for describing the common interface shared by all instances .
  • Specific products (ConcreteProduct): Is the goal of creating a simple factory pattern .

Its structure is shown in the figure below .

Java Technical debt

The code is as follows :

public class Client {

public static void main(String[] args) {

}
// Abstract product 
public interface Product {

void show();
}
// Specific products :ProductA
static class ConcreteProduct1 implements Product {

public void show() {

System.out.println(" Specific products 1 Show ...");
}
}
// Specific products :ProductB
static class ConcreteProduct2 implements Product {

public void show() {

System.out.println(" Specific products 2 Show ...");
}
}
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;
}
}
}

Factory method model

summary

In real life, social division of labor is more and more detailed , More and more specialized . All kinds of products are produced in special factories , We bid farewell to the era of self-sufficient small-scale peasant economy , This greatly shortens the production cycle of the product , Improved productivity . Again , Can the production and use of software objects be separated in software development ? Can it be satisfied in the future “ Opening and closing principle ” Under the premise of , Customers can add, delete or change the use of software related objects at will ? That's what we're going to talk about in this section .

stay 《 Simple factory model 》 In this section, we introduce the simple factory model , It's mentioned that the simple factory mode violates the open close principle , and “ Factory method model ” It's a further abstraction of the simple factory pattern , The advantage is that the system can introduce new products without modifying the original code , That is to meet the opening and closing principle .

Advantages and disadvantages

advantage :

  • Users only need to know the name of the specific factory to get the products they want , No need to know the specific creation process of the product .
  • Increased flexibility , For the creation of new products , Just write one more factory class .
  • A typical decoupling framework . High level modules only need to know the abstract class of the product , Don't care about other implementation classes , Satisfy the Dimitar rule 、 Rely on the inversion principle and the Ritz substitution principle .

shortcoming :

  • It's easy to have too many classes , Increase complexity
  • Increases the abstractness of the system and the difficulty of understanding
  • Abstract products can only produce one product , This drawback can be solved by using the abstract factory pattern .

Application scenarios

  • The customer only knows the name of the factory that created the product , I don't know the specific product name . Such as TCL TV factory 、 Hisense TV factory, etc .
  • The task of creating objects is done by one of several specific sub factories , The abstract factory only provides the interface to create products .
  • The customer doesn't care about the details of creating the product , Only care about the brand of the product

The structure and implementation of patterns

The factory method pattern consists of abstract factories 、 Specific factory 、 Abstract products and concrete products, etc 4 The elements make up . This section analyzes its basic structure and implementation method .

1. The structure of the pattern

The main roles of the factory approach pattern are as follows .

  1. Abstract factory (Abstract Factory): Provides an interface for creating products , The factory method through which the caller accesses a specific factory newProduct() To create a product .
  2. Specific factory (ConcreteFactory): It mainly implements the abstract methods in the abstract factory , Complete the creation of specific products .
  3. Abstract product (Product): Define the specifications of the product , The main features and functions of the product are described .
  4. Specific products (ConcreteProduct): Implemented the interface defined by the abstract product role , Created by a specific factory , It corresponds to specific factories one by one .

Java Technical debt

2. The realization of pattern

The code is as follows :

package FactoryMethod;
public class AbstractFactoryTest {

public static void main(String[] args) {

try {

Product a;
AbstractFactory af;
af = (AbstractFactory) ReadXML1.getObject();
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();
}
// Specific products 1: Implementing abstract methods in abstract products 
class ConcreteProduct1 implements Product {

public void show() {

System.out.println(" Specific products 1 Show ...");
}
}
// Specific products 2: Implementing abstract methods in abstract products 
class ConcreteProduct2 implements Product {

public void show() {

System.out.println(" Specific products 2 Show ...");
}
}
// Abstract factory : The method of producing factory products is provided 
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 Generate --> 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 factory 2 Generate --> Specific products 2...");
return new ConcreteProduct2();
}
}
package FactoryMethod;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
class ReadXML1 {

// This method is used to obtain the information from XML Extract the specific class name from the 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"));
// Get 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 by class name and return it to 
Class<?> c = Class.forName(cName);
Object obj = c.newInstance();
return obj;
} catch (Exception e) {

e.printStackTrace();
return null;
}
}
}

The program runs as follows :

 Specific factory 1 Generate --> Specific products 1...
Specific products 1 Show ...

If you will XML In the configuration file ConcreteFactory1 Change it to ConcreteFactory2, The result of the program is as follows :

 Specific factory 2 Generate --> Specific products 2...
Specific products 2 Show ...

Abstract factory pattern

summary

Previously introduced Factory method model In consideration of the production of a class of products , Such as livestock ranch, which only keeps animals 、 The TV factory only produces TV sets 、 The school of computer software only trains students majoring in computer software .

The same kind is called the same grade , in other words : Factory method model Only consider producing products of the same grade , But in real life, many factories are comprehensive factories , Can produce many grades ( species ) Products , Such as raising animals and plants on the farm , The electrical factory produces both TV sets and washing machines or air conditioners , The university has both software and biology majors .

The abstract factory model introduced in this section will consider the production of multi-level products , A group of products in different grades produced by the same specific factory is called a product family , chart 1 This is Haier factory and TCL The relationship between the TV set and the air conditioner produced by the factory .

Java Technical debt

The definition and characteristics of patterns

Definition

It is an interface for access classes to create a set of related or interdependent objects , And access classes do not need to specify the specific class of the desired product to get the pattern structure of different levels of products of the same family .

The abstract factory pattern is an upgraded version of the factory method pattern , The factory method mode produces only one level of products , And the abstract factory model can produce multiple levels of products .

Using the abstract factory pattern generally meets the following conditions .

  • There are multiple product families in the system , Each specific plant creates products of the same family but of different hierarchies .
  • The system can only consume one family of products at a time , That is to say, the products of the same family are used together .

Abstract factory pattern has the advantages of factory method pattern , Other main advantages are as follows :

  • You can manage the multi-level products associated with the product family within the class , You don't need to introduce multiple new classes for management .
  • When a product family is needed , Abstract factory can ensure that the client always uses only the product group of the same product .
  • Abstract factories enhance the extensibility of programs , When adding a new product family , No need to modify the original code , It satisfies the open close principle .

The drawback is that : When a new product needs to be added to the product family , All factory classes need to be modified . Increases the abstractness of the system and the difficulty of understanding .

The structure and implementation of patterns

The abstract factory pattern is the same as the factory method pattern , Also by the abstract factory 、 Specific factory 、 Abstract products and concrete products, etc 4 The elements make up , But the number of methods in the abstract factory is different , The number of abstract products is also different . Now let's analyze its basic structure and implementation method .

1. The structure of the pattern

The main roles of the abstract factory pattern are as follows .

  1. Abstract factory (Abstract Factory): Provides an interface for creating products , It contains multiple ways to create products newProduct(), You can create many different levels of products .
  2. Specific factory (Concrete Factory): It mainly implements multiple abstract methods in the abstract factory , Complete the creation of specific products .
  3. Abstract product (Product): Define the specifications of the product , The main features and functions of the product are described , The abstract factory pattern has multiple Abstract products .
  4. Specific products (ConcreteProduct): Implemented the interface defined by the abstract product role , Created by a specific factory , It has a many to one relationship with a specific factory .

Java Technical debt

2. The realization of pattern

It can be seen from the figure that the structure of the abstract factory pattern is similar to that of the factory method pattern , The difference is that there is more than one product type , So there's more than one way to create a product . Here is the code for the abstract factory and the concrete factory .

(1) Abstract factory : It provides the generation method of products .

interface AbstractFactory {

public Product1 newProduct1();
public Product2 newProduct2();
}

(2) Specific factory : The product generation method is realized .

class ConcreteFactory1 implements AbstractFactory {

public Product1 newProduct1() {

System.out.println(" Specific factory 1 Generate --> Specific products 11...");
return new ConcreteProduct11();
}
public Product2 newProduct2() {

System.out.println(" Specific factory 1 Generate --> Specific products 21...");
return new ConcreteProduct21();
}
}

Application scenario of the pattern

Abstract factory pattern was first used to create windows components belonging to different operating systems .

The abstract factory pattern is usually applied to the following scenarios :

  1. When the objects to be created are a series of interrelated or interdependent product families , Such as the TV set in the electrical factory 、 Washing machine 、 Air conditioning etc. .
  2. There are multiple product families in the system , But use only one family of products at a time . If someone only likes to wear clothes and shoes of a certain brand .
  3. Class library of products is provided in the system , And all products have the same interface , The client does not depend on the creation details and internal structure of the product instance .

The expansion of the pattern

There is a certain extension of the abstract factory pattern “ Opening and closing principle ” Tilt :

  1. When adding a new product family, you just need to add a new specific factory , No need to modify the original code , It satisfies the open close principle .
  2. When a new kind of product needs to be added to the product family , All factory classes need to be modified , Does not meet the opening and closing principle .

On the other hand , When there is only one hierarchical product in the system , Abstract factory pattern will degenerate into factory method pattern .

The author of this article :Java Technical debt
Link to the original text :https://www.cuizb.top/myblog/article/1655820677
Copyright notice : All articles in this blog except special statement , All adopt CC BY 3.0 CN License by agreement . For reprint, please sign the author and indicate the source of the article .

 Insert picture description here
JVM Causes of memory leaks and memory overflows
JVM Interpretation and use of common monitoring tools
Redis Frequently asked questions ( One )
ClickHouse And MaterializeMySQL engine ( Ten )
Implementation and difference of three distributed locks
Understanding and use of thread pool

Out of order ! Out of order !

Recent interview BAT, Organize an interview document , covers Java The core technology 、JVM、Java Concurrent 、SSM、 Microservices 、 database 、 Data structure, etc . Want to get ? If you want to improve yourself , And want to make progress with excellent people , Interested friends , You can scan the code below the official account. . The information is lying in the official account. ...

  • Collect if you like
  • Agree and praise
  • Support is concerned about
  • If in doubt, comment

Four in one , Yours offer Also four even

————————————————————————————————————————————————————————————————

copyright:author[Java technology debt],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/175/202206240208283083.html