当前位置:网站首页>New can also create objects. Why do you need factory mode?
New can also create objects. Why do you need factory mode?
2022-07-24 17:49:00 【User 6557940】
In the design pattern , Factory pattern is a kind of creative design pattern . In order to follow the opening and closing principles of software design and development , A simple factory model has been derived , Factory method pattern and abstract factory pattern . As a creative design pattern , Factory pattern is used to create new objects . So here's the problem , With C++ For example ,C++ The class constructor of can also create new objects , Why do we have to introduce the factory model ?
Encapsulate the initialization work when creating objects
If you use C Language , The tasks assigned and initialized include :
- malloc Application memory ( But the application object is not initialized , Just have a piece of memory space ), And force type conversion
- Initialize this memory
- Do other works
There seems to be some trouble , Allocate memory 、 Type conversion 、 initialization . If it is C++,new The action of includes two steps: allocating memory and calling constructor , Relatively simplified . This is a simple object for the general initialization process . What if the initialization process is complicated ? What is a complicated initialization process ? That is to say Creating objects is not just about allocating memory space , There are other initialization tasks to be done , Even work related to external variables or resources .
The following code is NVDLA Of compiler Part of the source code of :
SDPScaleOpNode* NodeFactory::newSDPScaleOpNode
(
ScaleNode* origCanNode,
Graph* engGraph
)
{
B b;
DD dd;
NvU16 numBatches = engGraph->profile()->multiBatchSize();
b = dd = new SDPScaleOpNode(origCanNode, numBatches);
dd->setName(std::string("sdp-scale-") + toString(s_sdp_scale_priv.size()));
dd->setId(engGraph->nextNodeId());
dd->setGraph(engGraph);
engGraph->insertNode(b);
s_sdp_scale_priv.insert(std::pair<B, DD>(b, dd));
return dd;
}I deleted part of the code for observation . This interface is to create a SDPScaleOpNode, But encapsulated in NodeFactory Of newSDPScaleOpNode() In the interface . In this interface, except
new SDPScaleOpNode(origCanNode, numBatches);outside , There's more setter and insert Work . If factory mode packaging is not used , Then every time you create one node, Must be created node Write other setter and insert Code for , Not easy to read , And cause code redundancy .
The following code is tensorflow A fragment in the source code . You can see , establish device The initialization process of is more complex , You can even handle some exceptions .
std::unique_ptr<Device> DeviceFactory::NewDevice(const string& type,
const SessionOptions& options,
const string& name_prefix) {
auto device_factory = GetFactory(type);
if (!device_factory) {
return nullptr;
}
SessionOptions opt = options;
(*opt.config.mutable_device_count())[type] = 1;
std::vector<std::unique_ptr<Device>> devices;
TF_CHECK_OK(device_factory->CreateDevices(opt, name_prefix, &devices));
int expected_num_devices = 1;
auto iter = options.config.device_count().find(type);
if (iter != options.config.device_count().end()) {
expected_num_devices = iter->second;
}
DCHECK_EQ(devices.size(), static_cast<size_t>(expected_num_devices));
return std::move(devices[0]);
}Unify the naming of the interface for creating objects
With the above example , It's easier to understand “ Unified interface naming ” 了 .
- If it is class Football, Then the creation is to new Football;
- If you create Basketball, Must new Basketball;
- If it is Volleyball, be new VolleyBall;
- If it is AbcdEfgHijkOpq1234567, be new AbcdEfgHijkOpq1234567( The name of the class is very long ).
If there is factory mode for packaging , Then it becomes
createFootball();
createBasketball();
createVolleyball();
createAbcdEfgHijkOpq1234567();The interface name is very clear , And you can probably know its function by function name .
Whether the object really needs “ establish ”?
Every time new, Will allocate memory ( Not to mention placement new). But in some cases , Do we really need to allocate memory every time ? To get a thread from the thread pool , To get a piece of memory from the memory pool , To get a resource from a resource pool , These resources have their own , There is no need to reassign , Unless the resources in the pool are used up . So another function of the factory model is , Control the timing of some resource allocation , When you really need to allocate memory , To allocate .
Binding polymorphism , To facilitate extension
Factory mode combined with polymorphism , Defines an interface for creating objects , But let subclasses decide which class to instantiate , Increase the flexibility of the code . For example, the following code , Through a unified interface getSportProduct(), Different products can be created at runtime .
int test()
{
AbstractFactory *fac = NULL;
AbstractSportProduct *product = NULL;
fac = new BasketballFactory();
product = fac->getSportProduct();
fac = new FootballFactory();
product = fac->getSportProduct();
fac = new VolleyballFactory();
product = fac->getSportProduct();
// other work
return 0;
}边栏推荐
- 0625~<config>-<bus>
- 邻接表的定义和存储以及有向图无向图的邻接存储
- NPM install reported -4058 error
- Six ways for JS to implement inheritance
- Two dimensional convolution -- use of torch.nn.conv2d
- After separation, the impression notes are still difficult to live, but there are many coquettish operations
- List of stringutils and string methods
- How the computer accesses the Internet (IV) LAN and server response
- 使用matplotlib模拟线性回归
- Use Matplotlib to simulate linear regression
猜你喜欢

Mobile robot (IV) four axis aircraft

使用Prometheus+Grafana监控MySQL性能指标

Ipaylinks, a cross-border payment integration service, won the 3A Asia Award of treasury

ROC and AUC details of the recommended system

SSM framework learning

Analog electricity - what is the resistance?
How to remove the top picture of the bubble skin article details of solo blog

Getaverse, a distant bridge to Web3

700. Search DFS method in binary search tree

Brats18 - Multimodal MR image brain tumor segmentation challenge continued
随机推荐
Tensorflow introductory tutorial (40) -- acunet
es(1)
Shengxin commonly used analysis graphics drawing 02 -- unlock the essence of volcano map!
使用Prometheus+Grafana监控MySQL性能指标
wallys/IPQ8074A 4x4 2.4G 8x8 5G 802.11ax
[network security] analysis vulnerability of website Middleware
Dry goods | three sub domain name collection tools worth collecting
还在用命令行看日志?快用Kibana吧,可视化日志分析YYDS!
awk从入门到入土(17)awk多行写法
Nearly 30 colleges and universities were named and praised by the Ministry of education!
如何遵循“低耦合”设计原则?
C language custom types - Enumeration
C语言编程训练题目:左旋字符串中的k个字符、小乐乐与欧几里得、打印箭型图案、公务员面试、杨树矩阵
Trends of semiconductor industry
Getaverse, a distant bridge to Web3
How to remove the top picture of the bubble skin article details of solo blog
Codeforces Round #794 (Div. 2)(A.B.C)
C # print reports using fastreport.net
int8 & int8,你栽过这样的跟头吗?
Preliminary understanding of redis