[英]factory design pattern issue
Suppose there is a factory as below. 假设有一家工厂,如下所示。 I would like to know if it is possible not to include ObjectA.h and ObjectB.h.
我想知道是否可以不包含ObjectA.h和ObjectB.h。
directory structure 目录结构
factory 厂
|-----ObjectA | ----- ObjectA
|-----ObjectB | ----- ObjectB
Since I don't want to include the header file in the sub-directory, is there any way to do so? 由于我不想在子目录中包含头文件,因此有什么办法吗? And if there is a new objectC, it does not need to modify the factory class.
并且如果有一个新的objectC,则不需要修改工厂类。 it will automatically create ObjectC if the type is "TypeC".
如果类型为“ TypeC”,它将自动创建ObjectC。
#include "ObjectA.h"
#include "ObjectB.h"
object* create(const string& type)
{
if (type == "typeA")
{
return new ObjectA();
}
else
{
return new ObjectB();
}
};
Yes, separate the implementation to an implementation file and only include the files there, providing solely the function prototype in the header. 是的,将实现与实现文件分开,仅在其中包含文件,仅在标头中提供功能原型。
To actually call new ObjectA();
实际调用
new ObjectA();
and new ObjectB();
和
new ObjectB();
you have to include the definitions in the calling site. 您必须在呼叫站点中包括这些定义。
//factory.h
object* create(const string& type);
//factory.cpp
#include "factory.h"
#include "ObjectA.h"
#include "ObjectB.h"
object* create(const string& type)
{
if (type == "typeA")
{
return new ObjectA();
}
else
{
return new ObjectB();
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.