当前位置:网站首页>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
边栏推荐
- faster-rcnn 训练自己的数据集
- Host PSQL connecting virtual machine Oracle
- Mysql8 encountered the problem of stopping after the service was started
- 若依 this.$router.push 同地址不同参,页面不刷新问题
- Leetcode 223. rectangular area
- 2022/7/18 CF training
- After data management, the quality is still poor
- If this.$router Push the same address with different parameters, and the page does not refresh
- “天上天下,唯我独尊”——单例模式
- After taking aiyouteng's medicine, Naifei's condition improved
猜你喜欢

31 next spread

Telephone system rules

Dynamics crm: mailbox configuration (III) - configure email server profiles and mailboxes

torch_ How to use scatter. Scatter() in detail

22 bracket generation

Leetcode 223. 矩形面积

2.19 haas506 2.0 development tutorial - Bluetooth - Bluetooth communication (only supports versions above 2.2)

faster-rcnn 训练自己的数据集

Urban safety series popular science - enter the high incidence period of drowning, if you know the common sense of life-saving

有了这个机器学习画图神器,论文、博客都可以事半功倍了!
随机推荐
Replace the image source of Debian full version with Alibaba cloud image source
LaneATT
Kubernetes version docking object storage
105 constructing binary trees from preorder and inorder traversal sequences
多线程(基础)
Software recommendation - Mechanical Major
Using JS to implement click events
【LeetCode】Day103-搜索二维矩阵 II
TCP协议调试工具TcpEngine V1.3.0使用教程
C TCP client form application asynchronous receiving mode
About SQL data query statements
yolov3 训练自己的数据集
Dynamics 365: how to get the threshold value of executemullerequest in batch requests
Software - prerequisite software
Best practices for preventing XSS in PHP web applications
Dynamics 365: how to get the authentication information required to connect to D365 online from azure
Hard core innovation that database needs to care about in the future
Traverse, delete, judge whether JSON data is empty, and recursion
Princeton calculus reader 02 Chapter 1 -- composition of functions, odd and even functions, function images
Introduction to bermudagrass