当前位置:网站首页>2. factory mode
2. factory mode
2022-06-12 10:12:00 【A man who is rubbed on the ground by math every day】
List of articles
Factory mode ( Frequency of use :*****)
Simple factory method code :
class LoggerFactory {
// Static factory method
public static Logger createLogger(String args) {
if(args.equalsIgnoreCase("db")) {
// Connect to database , Code ellipsis
// Create a database logger object
Logger logger = new DatabaseLogger();
// Initialize the database logger , Code ellipsis
return logger;
}
else if(args.equalsIgnoreCase("file")) {
// Create a log file
// Create a file logger object
Logger logger = new FileLogger();
// Initialize the file logger , Code ellipsis
return logger;
}
else {
return null;
}
}
}
Although the simple factory pattern separates the creation and use of objects , But there are still two problems :
(1) The factory class is too large , It contains a lot of if…else… Code , It makes maintenance and testing more difficult ;
(2) System expansion is not flexible , If you add a new type of logger , The business logic of the static factory method must be modified , Violation Contrary “ Opening and closing principle ”.
(3) , In simple factory mode , All products are created by the same factory , Factory jobs Heavy responsibility , The business logic is more complex , The coupling between specific products and factory classes is high , It seriously affects the flexibility of the system And scalability ,
The factory method model can solve this problem well .
1. Overview of the factory approach pattern ( A specific factory corresponds to a specific product )
In the factory method pattern , We no longer provide a unified factory class to create all product objects , But for different Our products are available in different factories , The system provides a factory hierarchy corresponding to the product hierarchy . Factory method model The definition is as follows :
Factory method model (Factory Method Pattern): Defines an interface for creating objects , Let subclasses decide which Class instantiation . The factory method pattern delays the instantiation of a class to its subclasses . Factory method mode is also called factory mode (Factory Pattern), Also known as virtual constructor pattern (Virtual Constructor Pattern) Or polymorphic factory mode (Polymorphic Factory Pattern). The factory method pattern is a kind of creation pattern .
The factory method pattern provides an abstract factory interface to declare abstract factory methods , The factory side is realized by its subclasses Law , Create specific product objects .

2. Role of factory methods
- Product( Abstract product )
- ConcreteProduct( Specific products )
- Factory( Abstract factory )
- ConcreteFactory( Specific factory )
Typical abstract factory code
public interface Factory {
public Product factoryMethod();
}
Typical specific factory
public class ConcreteFactory implements Factory {
public Product factoryMethod() {
return new ConcreteProduct();
}
}
Typical client code
……
Factory factory;
factory = new ConcreteFactory(); // It can be realized through configuration file and reflection mechanism
Product product;
product = factory.factoryMethod();
……
Assign values to concrete factories through abstract factories , Then specific products are created by specific factories
3. Examples of factory methods

Before using the configuration file and reflection mechanism , Changing a specific factory class requires modifying the client source code , But there is no need to modify the class library code
4. The configuration file
Plain text file , for example XML file ,properties file …… etc.
Usually XML file , You can store the class name in the configuration file , For example, the class name of a specific factory class
<!— config.xml -->
<?xml version="1.0"?>
<config>
<className>designpatterns.factorymethod.FileLoggerFactory</className>
</config>
xml Read
package designpatterns.factorymethod;
//XMLUtil.java
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import java.io.*;
public class XMLUtil {
// 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 getBean() {
try {
// establish DOM Document object
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dFactory.newDocumentBuilder();
Document doc;
doc = builder.parse(new File("src//designpatterns//factorymethod//config.xml"));
// Get the text node containing the class name
NodeList nl = doc.getElementsByTagName("className");
Node classNode=nl.item(0).getFirstChild();
String cName=classNode.getNodeValue();
// 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;
}
}
}
Client code
package designpatterns.factorymethod;
public class Client {
public static void main(String args[]) {
LoggerFactory factory;
Logger logger;
factory = (LoggerFactory)XMLUtil.getBean(); //getBean() The return type of is Object, You need to cast
logger = factory.createLogger();
logger.writeLog();
}
}
5. Steps to add new products
Steps to add new products
(1) Add a new concrete product class as a subclass of the abstract product class
(2) Add a new concrete factory class as a subclass of the abstract factory class , This factory is used to create new specific product objects
(3) Modify the configuration file , Replace the original factory class name string with the class name string of the new specific factory class
(4) Compile and add specific product classes and specific factory classes , Run the client code , The addition and use of new products can be completed
6. Overloading of factory methods

Abstract factory code
public interface LoggerFactory {
public Logger createLogger();
public Logger createLogger(String args);
public Logger createLogger(Object obj);
}
public class DatabaseLoggerFactory implements LoggerFactory {
public Logger createLogger() {
// Connect to the database by default , Code ellipsis
Logger logger = new DatabaseLogger();
// Initialize the database logger , Code ellipsis
return logger;
}
public Logger createLogger(String args) {
// Using parameter args Connect to the database as a connection string , Code ellipsis
Logger logger = new DatabaseLogger();
// Initialize the database logger , Code ellipsis
return logger;
}
public Logger createLogger(Object obj) {
// Use encapsulated in parameters obj Connect to the database using the connection string in , Code ellipsis
Logger logger = new DatabaseLogger();
// Use encapsulated in parameters obj To initialize the database logger , Code ellipsis
return logger;
}
}
// Other specific factory class codes are omitted
7. Hidden factory methods
Purpose : In order to further simplify the use of clients
Realization : Directly call the business methods of the product class in the factory class , The client does not need to call the factory method to create the product object , Directly using the factory object can call the business method in the created product object

Abstract factory class LoggerFactory Schematic code :
// Change the interface to an abstract class
public abstract class LoggerFactory {
// Directly call the business method of the logger class in the factory class writeLog()
public void writeLog() {
Logger logger = this.createLogger();
logger.writeLog();
}
public abstract Logger createLogger();
}
Client code
public class Client {
public static void main(String args[]) {
LoggerFactory factory;
factory = (LoggerFactory)XMLUtil.getBean();
factory.writeLog(); // Directly use the factory object to call the business method of the product object
}
}
The advantages and disadvantages of the factory approach
Pattern advantages
- The factory method is used to create the product the customer needs , It also hides from the customer the details of which specific product classes will be instantiated
- Let the factory decide what kind of product object to create , The details of how to create this object are completely encapsulated inside the specific factory
- When adding new products to the system , Fully comply with the opening and closing principle
shortcoming
The number of classes in the system will increase in pairs , To a certain extent, it increases the complexity of the system , It will bring some extra cost to the system
Increases the abstractness of the system and the difficulty of understanding
Use factory objects to call business methods of product objects
}
}
# The advantages and disadvantages of the factory approach
1. Pattern advantages
* The factory method is used to create the product the customer needs , It also hides from the customer the details of which specific product classes will be instantiated
* Let the factory decide what kind of product object to create , The details of how to create this object are completely encapsulated inside the specific factory
* When adding new products to the system , Fully comply with the opening and closing principle
2. shortcoming
* The number of classes in the system will increase in pairs , To a certain extent, it increases the complexity of the system , It will bring some extra cost to the system
* Increases the abstractness of the system and the difficulty of understanding
边栏推荐
- 7-13 underground maze exploration (adjacency table)
- Introduction to IOT
- Antique mfc/gdi+ Frame LCD display control
- 7-4 network red dot punch in strategy (DFS)
- [CEGUI] font resource loading process
- How CEPH improves storage performance and storage stability
- [Mozilla] basic concept analysis of IPDL
- Introduction to on-line circuit simulation and open source electronic hardware design
- np.meshgrid()函数 以及 三维空间中的坐标位置生成 以及 numpy.repeat()函数介绍
- Auto. JS debugging: use the network mode of lightning simulator for debugging
猜你喜欢

1268_ Implementation of FreeRTOS task context switching
![[Wayland] Weston multi screen display](/img/58/698e2cc790d3dbef9260cb2ad690d8.jpg)
[Wayland] Weston multi screen display

MYSQL的最左匹配原則的原理講解

Strange error -- frame detected by contour detection, expansion corrosion, and reversal of opening and closing operation effect
Detailed explanation and use of redis data types: key and string types

Auto. JS learning notes 7: JS file calls functions and variables in another JS file to solve various problems of call failure

Research on autojs wechat: the control IP in wechat on different versions of wechat or simulators is different.

2021-03-26
![[CEGUI] concept introduction](/img/a6/695d7f1a4e57c8438e2d1a4cad11dc.jpg)
[CEGUI] concept introduction

Web3.0与数字时尚,该如何落地?
随机推荐
002: what are the characteristics of the data lake
MySQL 7 affair
JVM (V) Virtual machine class loading (parental delegation mechanism)
The white paper "protecting our digital heritage: DNA data storage" was released
markdown_图片并排的方案
There is always a negative line (upper shadow line) that will stop the advance of many armies, and there is always a positive line (lower shadow line) that will stop the rampant bombing of the air for
MySQL optimized slow log query
MYSQL的最左匹配原則的原理講解
2021-02-22
Redis (II) Memory mapped data structure
np. Meshgrid() function and coordinate position generation in 3D space and numpy Introduction to repeat() function
postgresql 使用存储过程,拼接多张表,查询数据
[Wayland] Weston startup process analysis
HALCON联合C#检测表面缺陷——仿射变换(三)
Circuitbreaker fuse of resilience4j - circuitbreakerconfig configuration
Papaya Mobile has a comprehensive layout of cross-border e-commerce SaaS papaya orange. What are the opportunities for this new track?
How CEPH improves storage performance and storage stability
001: what is a data lake?
原始套接字使用
5 most common CEPH failure scenarios