工厂模式:typedef Class *(createClassFunction)(void)
Factory Pattern: typedef Class *(createClassFunction)(void)
typedef Class *(createClassFunction)(void)
(或typedef Class* (__stdcall *CreateClassFunction)(void)
的另一种变体)代表什么?这是什么意思?我该怎么解释呢?
读取C类型表达式
createClassFunction
是一个不接受参数并返回Class *
的函数的类型定义。
Class
的工厂。用法可能如下:
// the class factory
Class * MostTrivialFactoryKnownToMan()
{
return new Class;
}
// another class factory
Class * CreateClassWithLog()
{
ClassWithLog * p = new ClassWithLog; // derived from Class
p->SetLogFile("log.txt");
return p;
}
// code consuming the class factory
void PopulateStars(createClassFunction * factory)
{
// creates many instances of `Class` through `factory`
Sky * sky = GetSky();
for(int i=0; i<sky->GetStarCount(); ++i)
{
Class * inhabitant = (*factory)();
sky->GetStar(i)->SetInhabitant(inhabitant);
}
}
// code deciding which factory to use
const bool todayWeWriteALog = (rand() %2) != 0;
createClassFunction * todaysFactory = todayWeWriteALog ?
&MostTrivialFactoryKnownToMan :
&CreateClassWithLog);
PopulateStars(factory);
__stdcall
是在调用约定(参数和返回值如何在调用者和实现之间传递)中特定于编译器的属性更改。这通常对二进制兼容性很重要——例如,当Pascal程序需要调用用C或c++实现的函数时。
问题:
工厂函数返回一个原始指针。在工厂和消费者之间必须有一个如何释放指针的隐式契约(例如,通过或示例中的delete
)。使用智能指针(例如shared_ptr)作为返回类型将允许工厂决定删除策略。
作为函数指针的工厂可能不保存状态(例如日志文件名,它需要在函数中硬编码,或者全局可用)。使用可调用对象将允许实现可配置工厂。
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 在c++类上调用void函数
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 在派生函数中指定void*参数
- C++为什么尽管我调用了void函数,它却不起作用
- 如何从void函数输出字符串
- 我应该使用什么来代替void作为变体中的替代类型之一
- 奇怪的结构&GCC&clang(void*返回类型)
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 引用一个已擦除类型(void*)的指针
- 将尾部调用void(i32,..)位转换为llvm::函数以获取FnAttribute
- 库函数需要一个 std::function<void(void)>,如何传入类函数?
- 如何将指针从一个void函数传递到另一个C++
- 为什么我在使用void函数时得到错误代码C2276
- void*到驱动程序中的UnicodeString
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- 指针没有更新它在void函数内部指向的值
- 不能将 "void *" 类型的值分配给类型 "TCHAR" 的实体
- 错误:在为指针赋值时,void值没有被忽略