当前位置:网站首页>You really should go to the factory to move bricks!
You really should go to the factory to move bricks!
2022-07-24 16:18:00 【User 6557940】
introduction
Start with this article ,Jungle We will start to sort out and introduce them one by one 23 Design patterns .
01
Brief introduction of simple factory mode
The creation mode focuses on the creation process of objects , It is widely used in software development . The creation pattern describes how to separate the creation and use of objects , So that users do not need to care about the creation details of objects in the process of using objects , So as to reduce the system coupling , And make the system easy to modify and expand .
The simple factory pattern is one of the simplest design patterns , In fact, it does not belong to Gof Of 23 Design patterns , But the application is also very frequent , It is also the basis for the rest of the creation patterns , Therefore, it is necessary to learn the simple factory model first .
Simple factory application examples
What is the simple factory model ? for instance : Pictured above , A sporting goods factory ( This is a factory Factory), The factory can produce basketball according to customers' needs 、 Football and volleyball . Basketball 、 Football and volleyball are products (Product), The name of the product can be called a parameter . Customer Jungle Product parameters can be provided to the factory when necessary , The factory produces corresponding products according to product parameters , Customer Jungle There is no need to care about the details of the production process of the product .
1.2. Simple factory basic implementation process
From the above example , It is easy to summarize the implementation process of a simple factory :
- Design an abstract product class , It contains some implementations of public methods ;
- Multiple concrete product classes are derived from abstract product classes , Such as basketball 、 Football 、 Volleyball , The relevant codes for realizing the production of specific products in specific product classes ;
- Design a factory class , The factory class provides a factory method for producing various products , This method is based on the passed in parameters ( The product name ) Create different specific product class objects ;
- The customer only needs to call the factory method of the factory class , And pass in specific product parameters , You can get a specific product object .
Simple factory definition
Simple factory model : Define a simple factory class , It can return different instances according to different parameters , Instances created usually have a common parent class .
02
Simple factory model structure
As can be seen from the definition and examples of the simple factory pattern , In simple factory mode , In general, there is 3 A character :
- factory (Factory): According to the parameters of specific product categories provided by customers , Create a specific product instance ;
- Abstract product (AbstractProduct): Base class of specific product class , Contains public methods for creating products ;
- Specific products (ConcreteProduct): Derived classes of abstract products , Including specific product specific implementation methods , Is the goal of creating a simple factory pattern .
Simple factory model UML The class diagram is as follows :
03
Simple factory pattern code example
Consider the following scenario :
Jungle Want to do outdoor sports , It can choose to play basketball 、 Play football or volleyball . It needs to go to the sports storage room with a ticket , The name of a specific ball game is written on the ticket , such as “ Basketball ”. The person in charge of the sports storage room shall provide corresponding sporting goods according to the words on the ticket . then Jungle You can play happily
We use the simple factory pattern to implement the above scenario . First , The sports room is a factory , Basketball 、 Football and volleyball are concrete products , Abstract products can be defined as “ Sports ball products SportProduct”.Jungle As a customer, you only need to provide the specific product name , The factory can “ production ” Produce corresponding products .
Define abstract product classes AbstractProduct, Abstract methods do not provide an implementation
// Abstract product class AbstractProduct
class AbstractSportProduct
{
public:
AbstractSportProduct(){
}
// Abstract method :
void printName(){};
void play(){};
};Define three specific product classes
// Specific products Basketball
class Basketball :public AbstractSportProduct
{
public:
Basketball(){
printName();
play();
}
// Specific implementation method
void printName(){
printf("Jungle get Basketball\n");
}
void play(){
printf("Jungle play Basketball\n");
}
};
// Specific products Football
class Football :public AbstractSportProduct
{
public:
Football(){
printName();
play();
}
// Specific implementation method
void printName(){
printf("Jungle get Football\n");
}
void play(){
printf("Jungle play Football\n");
}
};
// Specific products Volleyball
class Volleyball :public AbstractSportProduct
{
public:
Volleyball(){
printName();
play();
}
// Specific implementation method
void printName(){
printf("Jungle get Volleyball\n");
}
void play(){
printf("Jungle play Volleyball\n");
}
};Define factory classes and factory methods
class Factory
{
public:
AbstractSportProduct *getSportProduct(string productName)
{
AbstractSportProduct *pro = NULL;
if (productName == "Basketball"){
pro = new Basketball();
}
else if (productName == "Football"){
pro = new Football();
}
else if (productName == "Volleyball"){
pro = new Volleyball();
}
return pro;
}
};Examples of client usage
#include <iostream>
#include "SimpleFactory.h"
int main()
{
printf(" Simple factory model \n");
// Define factory class objects
Factory *fac = new Factory();
AbstractSportProduct *product = NULL;
product = fac->getSportProduct("Basketball");
product = fac->getSportProduct("Football");
product = fac->getSportProduct("Volleyball");
system("pause");
return 0;
}effect :
You can see , When used on the client side , You only need to provide the product name as a parameter , Into the method of the factory , You can get the corresponding product . There is no implementation of public methods provided in the abstract product class , Instead, it is implemented in each specific product category according to their respective product conditions .
04
Summary of the simple factory model
The advantage of the simple factory model is :
- The factory class provides methods for creating specific products , And contains certain judgment logic , Customers do not have to participate in the product creation process ;
- The customer only needs to know the parameters of the corresponding product , Parameters are generally simple and easy to remember , Like numbers 、 Characters or strings, etc .
Of course , The simple factory model has obvious shortcomings ( Think about the object-oriented design principles we introduced earlier ???). Suppose one day Jungle Want to play baseball , What to do ? You are sure to say , Isn't that easy ? Then derive a... From the abstract product class Baseball class , And in the factory class getSportProduct Add “productName == "Baseball” The conditional branch of . That's true , But it's obvious Against the principle of opening and closing ( Open to expansion , Turn off for changes ), That is, the existing code is modified when extending the function . On the other hand , All the judgment logic of the simple factory pattern is implemented in the factory class , In case of plant design failure , Then the whole system will be affected !
So what should we do ? Look at the next episode !
Source code address :https://github.com/FengJungle/DesignPattern
边栏推荐
- OpenMP入门
- Yolov6 trains its own data set
- Fast RCNN trains its own data set
- Which is a good noise reduction Bluetooth headset? Ranking of the most cost-effective noise reduction Bluetooth headsets
- Leetcode:162. looking for peak [two points looking for peak]
- Lsyncd real time synchronization
- Software - prerequisite software
- Machine learning notes - building a recommendation system (5) feedforward neural network for collaborative filtering
- MySQL之知识点(十二)
- 2.19 haas506 2.0 development tutorial - Bluetooth - Bluetooth communication (only supports versions above 2.2)
猜你喜欢

Yolov3 trains its own data set

There are more than 20 categories of the four operators in MySQL. It took three days and three nights to sort them out. Don't collect them quickly

How to prevent XSS in PHP

【SWT】自定义数据表格

105 constructing binary trees from preorder and inorder traversal sequences

多线程(基础)
![Dynamics crm: [problem solved]cannot open SQL encryption symmetric key because symmetric key password](/img/ae/125fcb16c9d85714c7bbd1255d1d18.png)
Dynamics crm: [problem solved]cannot open SQL encryption symmetric key because symmetric key password

Some understanding of the rank sum of matrix and the rank of image

About SQL data query statements

LaneATT
随机推荐
Software - prerequisite software
R language ggplot2 visualization: ggplot2 visualization basic scatter plot, through in theme_ Specify the parameter base in BW_ Size to change the size of axis labels and control the size of gridlines
普林斯顿微积分读本02第一章--函数的复合、奇偶函数、函数图像
MySQL write lock does not take effect
Deploy ZABBIX monitoring system and email alarm mechanism in lamp architecture
降噪蓝牙耳机哪个好?性价比最高的降噪蓝牙耳机排行
The 3D sensing market is accelerating. Who will be better, TOF or structured light?
有了这个机器学习画图神器,论文、博客都可以事半功倍了!
Hard core innovation that database needs to care about in the future
31 next spread
MySQL之知识点(十二)
电话系统规则
Array in PHP_ The pit of merge
yolov3 训练自己的数据集
Wentai technology and Baoxin software deepened 5g cooperation, and 5g manufacturing settled in Baowu, China
torch_ How to use scatter. Scatter() in detail
Withdrawal of IPO application, Yunzhou intelligent "tour" of unmanned boat enterprise fails to enter the science and Technology Innovation Board
【SWT】滚动容器实现商品列表样式
Software recommendation - office software
By default, the select drop-down box selects the solution ligerui that the selected attribute does not work