当前位置:网站首页>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;
}边栏推荐
- Iqiyi Tiktok reconciled, Weibo lying gun?
- C # print reports using fastreport.net
- Eth POS 2.0 stacking test network pledge process
- DHCP relay of HCNP Routing & Switching
- C language custom type explanation - structure
- C language to achieve a static version of the address book
- High performance complexity analysis of wechat circle of friends
- Pay close attention! List of the latest agenda of 2022 open atom open source Summit
- C language programming training topics: K characters in left-handed string, little Lele and Euclidean, printing arrow pattern, civil servant interview, poplar matrix
- Nearly 30 colleges and universities were named and praised by the Ministry of education!
猜你喜欢
随机推荐
Polymorphism, abstract class, interface
es(1)
Brats18 - Multimodal MR image brain tumor segmentation challenge continued
213. 打家劫舍 II-动态规划
Explain Apache Hudi schema evolution in detail
C语言编程训练题目:左旋字符串中的k个字符、小乐乐与欧几里得、打印箭型图案、公务员面试、杨树矩阵
Mobile robot (IV) four axis aircraft
阿里巴巴/166获得店铺的所有商品 API使用说明
Common questions of testers during interview
How the computer accesses the Internet (IV) LAN and server response
Codeforces Round #794 (Div. 2)(A.B.C)
Use yarn
Common methods of number and math classes
Wallys/3 × 3/2 × 2 MIMO 802.11ac Mini PCIe Wi-Fi Module, Dual Band, 2,4GHz / 5GHz/QCN9074
com.mysql.cj.jdbc.exceptions. MySQLTransactionRollbackException: Deadlock found when trying to get lo
0615 ~ realize RBAC permission management with user-defined annotations
700. Search DFS method in binary search tree
JS image conversion Base64 Base64 conversion to file object
Openlayers: point aggregation effect
C语言中的字符与字符串库函数的使用以及模拟实现

![[wechat official account H5] authorization](/img/d1/2712f87e134c0b8b8fdeaab9e30492.png)







