Java technology debt 2022-06-24 07:28:17 阅读数:406
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 .
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 .
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 main roles of the simple factory model are as follows :
Its structure is shown in the figure below .
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;
}
}
}
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 .
advantage :
shortcoming :
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 .
The main roles of the factory approach pattern are as follows .
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 ...
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 .
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 .
Abstract factory pattern has the advantages of factory method pattern , Other main advantages are as follows :
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 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 .
The main roles of the abstract factory pattern are as follows .
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();
}
}
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 :
There is a certain extension of the abstract factory pattern “ Opening and closing principle ” Tilt :
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 .
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. ...
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